2011-04-09 133 views
4

對象變量我有PHP代碼,如:調用匿名函數定義爲PHP

class Foo { 
    public $anonFunction; 
    public function __construct() { 
    $this->anonFunction = function() { 
     echo "called"; 
    } 
    } 
} 

$foo = new Foo(); 
//First method 
$bar = $foo->anonFunction(); 
$bar(); 
//Second method 
call_user_func($foo->anonFunction); 
//Third method that doesn't work 
$foo->anonFunction(); 

有沒有在PHP的方式,我可以使用第三種方法調用定義爲類的屬性匿名函數?

謝謝

回答

9

不直接。 $foo->anonFunction();不起作用,因爲PHP會嘗試直接調用該對象的方法。它不會檢查是否有存儲可調用名稱的屬性。你可以攔截方法調用。

一下添加到類定義

public function __call($method, $args) { 
    if(isset($this->$method) && is_callable($this->$method)) { 
     return call_user_func_array(
      $this->$method, 
      $args 
     ); 
    } 
    } 

這種技術也

+0

感謝解釋,至少現在我知道這是不可能的,但通過可能解決方法。 – radalin 2011-04-09 14:41:35