2017-03-14 41 views
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()。這可能嗎?

回答

3

由於錯誤信息提示,您需要從您的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; 
    } 
} 
+0

魔術!謝謝,我以爲我試過這個..但顯然搞砸了。 – Arth