在PHP中调用作为对象变量定义的匿名函数

4

I have php code like:

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中,我是否可以使用第三种方法调用定义为类属性的匿名函数?

谢谢

1个回答

10

不能直接使用$foo->anonFunction();。因为PHP将尝试直接在该对象上调用该方法,而不会检查是否存在存储可调用的同名属性。不过,你可以拦截这个方法调用。

在类定义中添加以下内容:

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

此技术在以下文章中有详细解释:


谢谢,至少现在我知道这是不可能的,但可以通过一种变通的方式实现。 - radalin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接