php魔法设置器-修改的子属性
假设我们有以下PHP类:php魔法设置器-修改的子属性,php,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,
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。这就是我想要实现的
但是,如果修改是在对象值中完成的,是否有可能“跟踪”修改?例如:
$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,我想,您必须将新值传递给“set”函数。您这样做的方式只是更改值本身,而不进入您声明的函数,即“modified”变为true 也许像这样
$obj->someObject->__set($name, 'New Name');
也许我在这里走错了路,看看这个,我想这就是你想要的:我将为$property构建一个全新的类,而不是使用stdClass(),这样以后维护代码就容易多了,然后你就可以轻松实现你想要的。