php __set()重载方法意外行为

时间:2014-09-25 01:07:26

标签: php oop overloading

我有:

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为空。

对此行为的任何解释都会有所帮助,与官方文档的链接也会很好。

1 个答案:

答案 0 :(得分:1)

您的对象没有streetaddress属性,这就是为什么在您尝试设置$this->streetaddress = $maybenumber;时调用魔术方法__set的原因。

魔术方法:http://php.net/manual/en/language.oop5.magic.php