PHP5成员重载错误: Indirect modification of overloaded property has no effect
Posted in PHP on January 14th, 2010 by Adam出现如下错误:Class Foo{
private $arr;
public function __get($key) {
if(isset($this->arr[$key])){
return $this->arr[$key];
}
}public function __set($key, $val) {
if(isset($this->arr[$key])){
$this->arr[$key] = $val;
}
}
}
$f = new Foo;
$f->test = 1;
Notice: Indirect modification of overloaded property Foo::$arr has no effect根据Google结果:
[27 Sep 2007 8:16pm UTC] brjann at gmail dot com
It seems that declaring the getter as “public function &__get(){…}” does the trick. However, it took some googling to find.php magic __set and __get
this one works as expected. Actually php interpreter seems to do same thing. Trying to get value if exists and change it. Problem is that when it takes this value there is no place to store it and rise this error. Trying to modify property in not existing array. Solution is to make this array available. Returning values by reference seems to work.解决办法是给__get()加上引用传递&__get,
试图帮助函数找到引用被绑定的不存在的变量arr。但是这里存在没有调用__set的问题。public function &__get($key) {
return $this->arr[$key];
}
$f->array['test'] = 1;
我的办法是$arr转为公有化,放弃__set。
public $arr;
$f->arr['test'] = 1;