在php中调用匿名函数定义为对象变量

rad*_*lin 4 php class anonymous-function

我有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();
Run Code Online (Sandbox Code Playgroud)

有没有办法在PHP中我可以使用第三种方法来调用定义为类属性的匿名函数?

谢谢

Gor*_*don 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
         );
     }
  }
Run Code Online (Sandbox Code Playgroud)

该技术也在解释中