1
最近我遇到了以下問題。這是發生問題的簡單例子。__invoke對象引用丟失行爲
class a{
public function __invoke($classname){
return new $classname($this);
}
}
class b{
private $obj;
public function __construct($obj){
$this->obj = $obj;
}
public function getC(){
return $this->obj('c');
}
}
class c{}
$a = new a;
$a('b')->getC();
當我執行這個代碼,我得到以下錯誤
Fatal error: Call to undefined method b::obj()
看來__invoke的行爲失去了對對象的引用在此行
return $this->obj('c');
它實際上不對我來說這個大問題,因爲我可以這樣做
return $this->obj->__invoke('c');
..但我真的很想知道爲什麼__invoke在這裏無法按預期工作。任何人都可以解釋我嗎?提前致謝!
感謝您的答案,這實際上有效! – sofl