我有:
class Address {
private $number;
private $street;
public function __construct( $maybenumber, $maybestreet = null ) {
if( is_null( $maybestreet) ) {
$this->streetaddress = $maybenumber;
} else {
$this->number = $maybenumber;
$this->street = $maybestreet;
}
}
public function __set( $property, $value ) {
if( $property === "streetaddress" ) {
if( preg_match( "/^(\d+.*?)[\s,]+(.+)$/", $value, $matches ) ) {
$this->number = $matches[1];
$this->street = $matches[2];
} else {
throw new Exception( "unable to parse street address: '{$value}'" );
}
}
}
public function __get( $property ) {
if( $property === "streetaddress" ) {
return $this->number . " " . $this->street;
}
}
}
$address = new Address( "441b Bakers Street" );
echo "<pre>";
print_r($GLOBALS);
echo "</pre>";
输出:
...
[address] => Address Object
(
[number:Address:private] => 441b
[street:Address:private] => Bakers Street
)
当__set方法甚至无法从无处调用时,如何调用__set
方法以及属性$number
和$street
如何设置?
我的正常逻辑告诉我,当实例化发生时,所有会发生的事情是,创建一个属性streetaddress
,并将值传递给$maybenumber
参数,因为第二个参数,$maybestreet
为空。
对此行为的任何解释都会有所帮助,与官方文档的链接也会很好。
答案 0 :(得分:1)
您的对象没有streetaddress
属性,这就是为什么在您尝试设置$this->streetaddress = $maybenumber;
时调用魔术方法__set的原因。