How do I immediately execute an anonymous function in PHP?

PhpJavascriptFunction

Php Problem Overview


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

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

Can you do something like that in PHP?

Php Solutions


Solution 1 - Php

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'; })();

Solution 2 - Php

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:

1
2
3

Solution 3 - Php

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

<?php
// we simply need to write a simple function called run:
function run($f){
	$f();
}

// and then we can use it like this:
run(function(){
	echo "do something";
});

?>

Solution 4 - Php

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

Solution 5 - Php

(new ReflectionFunction(function() {
 // body function
}))->invoke();

Solution 6 - Php

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.]

Details:

<?php
# Tags: benchmark, call_user_func, anonymous function 
require_once("Benchmark.php");
bench(array(
        'test1_anonfunc_call' => function(){
                $f = function(){
                        $x = 123;
                };
                $f();
        },
        'test2_anonfunc_call_user_func' => function(){
                call_user_func(
                        function(){
                                $x = 123;
                        }
                );
        }
), 10000);
?>

Results:

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

Solution 7 - Php

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.

Solution 8 - Php

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();

Solution 9 - Php

Not executed inmediately, but close to ;)

<?php

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

?>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEmanuil RusevView Question on Stackoverflow
Solution 1 - PhpGordonView Answer on Stackoverflow
Solution 2 - PhpWallace MaxtersView Answer on Stackoverflow
Solution 3 - PhpPacerierView Answer on Stackoverflow
Solution 4 - PhpYasuo OhgakiView Answer on Stackoverflow
Solution 5 - PhpinnermondView Answer on Stackoverflow
Solution 6 - PhpShovasView Answer on Stackoverflow
Solution 7 - Phpthecoolestname36View Answer on Stackoverflow
Solution 8 - PhpPaul Jerome BordalloView Answer on Stackoverflow
Solution 9 - PhpJamesView Answer on Stackoverflow