javascript – How do I immediately execute an anonymous function in PHP?-ThrowExceptions

Exception or error:

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

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

Can you do something like that in PHP?

How to solve:

For PHP7: see Yasuo Ohgaki’s answer: (function() {echo 'Hi';})();

For previous versions: the only way to execute them immediately I can think of is

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


In PHP 7 is to do the same in javascript

$gen = (function() {
    yield 1;
    yield 2;

    return 3;

foreach ($gen as $val) {
    echo $val, PHP_EOL;

echo $gen->getReturn(), PHP_EOL;

The output is:



Well of course you can use call_user_func, but there’s still another pretty simple alternative:

// we simply need to write a simple function called run:
function run($f){

// and then we can use it like this:
    echo "do something";



This is the simplest for PHP 7.0 or later.

php -r '(function() {echo 'Hi';})();'

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


(new ReflectionFunction(function() {
 // body function


Note, accepted answer is fine but it takes 1.41x as long (41% slower) than declaring a function and calling it in two lines.

[I know it’s not really a new answer but I felt it was valuable to add this somewhere for visitors.]


# Tags: benchmark, call_user_func, anonymous function 
        'test1_anonfunc_call' => function(){
                $f = function(){
                        $x = 123;
        'test2_anonfunc_call_user_func' => function(){
                                $x = 123;
), 10000);


$ php test8.php
test1_anonfunc_call took 0.0081379413604736s (1228812.0001172/s)
test2_anonfunc_call_user_func took 0.011472940444946s (871616.13432805/s)


I tried it out this way, but it’s more verbose than the top answer by using any operator (or function) that allows you to define the function first:

    $value = $hack == ($hack = function(){
            // just a hack way of executing an anonymous function
            return array(0, 1, 2, 3);                
    }) ? $hack() : $hack();


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.


Not executed inmediately, but close to 😉


$var = (function(){ echo 'do something'; });


Leave a Reply

Your email address will not be published. Required fields are marked *