Anonymous function for object method

Possible duplicate:
Direct call closure for an object property

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

$a = 'a'; $tokenMapper->tokenJoinHistories = function($a) { echo $a; }; $tokenMapper->tokenJoinHistories($a); 
+6
source share
2 answers

Using $obj->foo() you call the methods, but you want to call the property as a function / method. This just confuses the parser because it did not find a method called foo() , but it cannot expect any property to be something called.

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

Or do you expand your cartographer, for example

 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 problems in this quick-written example)

0
source

PHP is trying to map an instance method called "tokenJoinHistories" that is not defined in the source class

Instead you should do

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

Read the documentation here , especially the comment part.

+2
source

Source: https://habr.com/ru/post/893266/


All Articles