开发者

Calling anonymous functions defined as object variables in php [duplicate]

This question already has answers here: Calling closure assigned to object property directly (12 answers) Closed 9 years ago.

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->anonFu开发者_开发技巧nction();

Is there a way in php that I can use the third method to call anonymous functions defined as class properties?

thanks


Not directly. $foo->anonFunction(); does not work because PHP will try to call the method on that object directly. It will not check if there is a property of the name storing a callable. You can intercept the method call though.

Add this to the class definition

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

This technique is also explained in

  • JavaScript-style object literals
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜