In JavaScript, you can define anonymous functions that are executed immediately:
(function () { /* do something */ })()
Can you do something like that in PHP?
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 () .
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.
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);
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!
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'; })();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With