6

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);
Community
  • 1
  • 1
Martin
  • 63
  • 2

2 Answers2

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.

Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
0

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)

KingCrunch
  • 128,817
  • 21
  • 151
  • 173