Declaring an anonymous function within new stdClass Declaring an anonymous function within new stdClass php php

Declaring an anonymous function within new stdClass


PHP is right when invoke fatal error Call to undefined method stdClass::city() because object $class->address('name') has no method city.Intead, this object has property city which is instance of Closure Class (http://www.php.net/manual/en/class.closure.php)You can verify this: var_dump($class->address('name')->city)

I found the way to call this anonymous function is:

$closure = $class->address('name')->city;$closure('class');

Hope this helps!


Sadly it is not possible within stdClass, but there is a workaround -- PHP Anonymous Object.

// define by passing in constructor$anonim_obj = new AnObj(array(    "foo" => function() { echo "foo"; },     "bar" => function($bar) { echo $bar; } ));$anonim_obj->foo(); // prints "foo"$anonim_obj->bar("hello, world"); // prints "hello, world"


AFAIK, this is not supported by PHP, and you must use the call_user_func() or call_user_func_array() functions to call closures assigned to class properties (usually you can use __call() to do this, but in your case, the class is stdClass, so this isn't possible).