我有这堂课:
class Foo {
private $_data;
public function __construct(array $data){
$this->_data = $data;
}
public function __get($name){
$getter = 'get'.$name;
if(method_exists($this, $getter)){
return $this->$getter();
}
if(array_key_exists($name,$this->_data)){
return $this->_data[$name];
}
throw new Exception('Property '.get_class($this).'.'.$name.' is not available');
}
public function getCalculated(){
return null;
}
}
getCalculated()
表示计算的属性。
现在,如果我尝试以下内容:
$foo = new Foo(['related' => []])
$foo->related[] = 'Bar'; // Indirect modification of overloaded property has no effect
$foo->calculated; // ok
但如果我将__get()
签名更改为&__get($name)
,我会:
$foo = new Foo(['related' => []])
$foo->related[] = 'Bar'; // ok
$foo->calculated; // Only variables should be passed by reference
我非常希望通过引用返回$data
元素,并在__get()
中按值获取getter。这可能吗?
答案 0 :(得分:4)
如错误消息所示,您需要从getter中返回一个变量:
class Foo {
private $_data;
public function __construct(array $data){
$this->_data = $data;
}
public function &__get($name){
$getter = 'get'.$name;
if(method_exists($this, $getter)){
$val = $this->$getter(); // <== here we create a variable to return by ref
return $val;
}
if(array_key_exists($name,$this->_data)){
return $this->_data[$name];
}
throw new Exception('Property '.get_class($this).'.'.$name.' is not available');
}
public function getCalculated(){
return null;
}
}