Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and invoking an anonymous function in a single statement

Tags:

closures

php

A php closure or anonymous function is used to create function without specifying its name.

Is it possible to call them without assigning to identifier as we do in JavaScript ? e.g.

(function(){
    echo('anonymous function');
})();

What is the correct use of use construct while defining anonymous function and what is the status of anonymous function in public method with accessibility to private properties?

$anon_func = 
function($my_param) use($this->object_property){ //use of $this is erroneous here
    echo('anonymous function');
};
like image 755
Shoaib Nawaz Avatar asked Aug 31 '10 02:08

Shoaib Nawaz


People also ask

How do you create 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.

How do we assign an anonymous function to a variable?

We write the anonymous function in Javascript by writing function() followed by the parentheses, where we may pass the parameters, and skipping the function name. Then in a pair of curly braces {}, we write our desired code. Finally, we assign this function to a variable.

What is anonymous function also give a code 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();


2 Answers

PHP 7 added the ability to do this.

This code:

(function() { echo "This works as expected in PHP 7.\n"; })();

works as one would expect in PHP 7. (It still doesn't work in any PHP 5.x. release)

like image 63
jbafford Avatar answered Sep 25 '22 00:09

jbafford


call_user_func(function() use(closure-vars){ ... });
like image 27
steampowered Avatar answered Sep 24 '22 00:09

steampowered