How do I immediately execute an anonymous function in PHP?

Viewed 20199

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

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

Can you do something like that in PHP?

9 Answers

This is the simplest for PHP 7.0 or later.

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

It means create closure, then call it as function by following "()". Works just like JS thanks to uniform variable evaluation order.

https://3v4l.org/06EL3

This isn't a direct answer, but a workaround. Using PHP >= 7. Defining an anonymous class with a named method and constructing the class and calling the method right away.

$var = (new class() { // Anonymous class
    function cool() { // Named method
        return 'neato';
    }
})->cool(); // Instantiate the anonymous class and call the named method
echo $var; // Echos neato to console.
Related