Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring an anonymous function within new stdClass

Just wondering why something like this doesn't work:

public function address($name){
    if(!isset($this->addresses[$name])){
        $address = new stdClass();
        $address->city = function($class = '', $style = ''){
            return $class;
        };          
        $this->addresses[$name] = $address;
    }
    return $this->addresses[$name];
}

Calling it like echo $class->address('name')->city('Class') should just echo Class, however I get Fatal error: Call to undefined method stdClass::city()

I can find a better way to do this, because this will get messy, but I'm wondering what I might be doing wrong there, or if PHP doesn't support this and why.

like image 278
Kavi Siegel Avatar asked Feb 20 '12 02:02

Kavi Siegel


People also ask

How do you make an anonymous function?

Anonymous Function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.

Does PHP have anonymous function?

Anonymous function is a function without any user defined name. Such a function is also called closure or lambda function. Sometimes, you may want a function for one time use. Closure is an anonymous function which closes over the environment in which it is defined.

What is anonymous function with example?

An anonymous function is a function that was declared without any named identifier to refer to it. As such, an anonymous function is usually not accessible after its initial creation. Normal function definition: function hello() { alert('Hello world'); } hello();

How can you pass a local variable to an anonymous function in PHP?

Yes, use a closure: functionName($someArgument, function() use(&$variable) { $variable = "something"; }); Note that in order for you to be able to modify $variable and retrieve the modified value outside of the scope of the anonymous function, it must be referenced in the closure using & . It's new!


1 Answers

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!

like image 188
Sergey Ratnikov Avatar answered Sep 23 '22 10:09

Sergey Ratnikov