Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I immediately execute an anonymous function in PHP?

In JavaScript, you can define anonymous functions that are executed immediately:

(function () { /* do something */ })() 

Can you do something like that in PHP?

like image 721
Emanuil Rusev Avatar asked Aug 25 '10 16:08

Emanuil Rusev


People also ask

How do you run an anonymous function?

The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .

How do you call a function automatically in PHP?

The only way to do this is using the magic __call . You need to make all methods private so they are not accessable from the outside. Then define the __call method to handle the method calls.

Does PHP have anonymous functions?

Anonymous functions, also known as closures , allow the creation of functions which have no specified name. They are most useful as the value of callable parameters, but they have many other uses. Anonymous functions are implemented using the Closure class. printf("Hello %s\r\n", $name);

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

For versions prior to PHP 7, the only way to execute them immediately I can think of is

call_user_func(function() { echo 'executed'; }); 

With current versions of PHP, you can just do

(function() { echo 'executed'; })(); 
like image 107
Gordon Avatar answered Sep 24 '22 17:09

Gordon