Anonymous function for a method of an object [duplicate]

五迷三道 提交于 2019-12-10 04:35:24

问题


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.



来源:https://stackoverflow.com/questions/6775774/anonymous-function-for-a-method-of-an-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!