0
我有這個類:PHP神奇的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)){
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
我會很喜歡引用和getter返回$data
元素按我的價值__get()
。這可能嗎?
魔術!謝謝,我以爲我試過這個..但顯然搞砸了。 – Arth