Anonymous function for a method of an object [dupl

2019-04-29 03:19发布

问题:

Possible Duplicate:
Calling closure assigned to object property directly

Why this is not possible in PHP? I want to be able to create a function on the fly for a particular object.

$a = 'a';
$tokenMapper->tokenJoinHistories = function($a) {
   echo $a;
};
$tokenMapper->tokenJoinHistories($a);

回答1:

With $obj->foo() you call methods, but you want to call a property as a function/method. This just confuses the parser, because he didn't find a method with the name foo(), but he cannot expect any property to be something callable.

call_user_func($tokenMapper->tokenJoinHistories, $a);

Or you extend your mapper like

class Bar {
  public function __call ($name, $args) {
    if (isset($this->$name) && is_callable($this->$name)) {
      return call_user_func_array($this->$name, $args);
    } else {
      throw new Exception("Undefined method '$name'");
    } 
  }
}

(There are probably some issues within this quickly written example)



回答2:

PHP tries to match an instance method called "tokenJoinHistories" that is not defined in the original class

You have to do instead

$anon_func = $tokenMapper->tokenJoinHistories;
$anon_func($a);

Read the documentation here especially the comment part.