2013-07-02 39 views
0

我想立即在新構建的對象上調用魔術方法(__call())。例如:對新PHP對象的即時1行魔術方法調用

class Foo { 
    public function __call($method,$args) { 
     echo "You were looking for the method $method.\n"; 
    } 
} 

理想(但得到解析錯誤):

$foo = new Foo()->bar(); // Fails :(

工作:

$foo = new Foo(); 
$foo = $foo->bar(); 

這可能嗎?我知道PHP 5.4帶來了即時的1行對象方法調用(http://docs.php.net/manual/en/migration54.new-features.php),所以我不知道爲什麼這不起作用。

+1

是否希望'$ foo'的值是'Foo'類的新實例或方法'bar'的返回結果? –

+0

來自方法「bar」的結果。 @ complex857有一個工作答案。 –

回答

4

你實際上只缺少一個()對,這個工程:

$foo = (new Foo())->bar(); // this works. 

在PHP 5.4的changelog它寫道:在實例

類成員訪問已被加入,例如(新 美孚→bar()。

+0

這不起作用,你測試過了嗎? –

+0

是的,[我有](http://codepad.viper-7.com/GJEa2F)。你確定你在使用PHP 5.4嗎? – complex857

+0

「那麼你的問題」 - 傑米Hyneman 我的不好,謝謝! –