2011-04-09 91 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