php magic setters - 修改了子属性

时间:2017-07-03 13:03:10

标签: php

让我们说,我们有以下PHP类:

class Product {
    protected $data = array();
    protected $modified = false;

    public function __construct($data) {
        $this->data = $data;
    }

    public function & __get($name) {
        if(array_key_exists($name, $this->data)) {
            return $this->data->$name;
        }

        $null = null;

        return $null;
    }

    public function __set($name, $value) {
        $this->data->$name = $value;
        $this->modified = true;
    }        
}
$obj = new Product([]);

如果我现在设置一个值(例如$obj->name = "Name";),则将类属性$ modified设置为true。这就是我想要的东西。

但它是否有可能,以及#34;追踪"修改,如果在对象值中完成?例如:

$property = new stdClass();
$property->name = "Name of Prop";
$obj = new Product([
    "name" => "Name",
    "someObject" => $property
]);

// Now here comes the change
$obj->someObject->name = "New Name";

因为使用上面的代码,$ obj-> modified将为false

1 个答案:

答案 0 :(得分:0)

我想,你必须将新值传递给“set”函数。你这样做只是改变了值本身,而没有进入你声明的函数,“modified”变为true。

喜欢这样吗?

$obj->someObject->__set($name, 'New Name');