如何在 PHP 中立即执行匿名函数?

在 JavaScript 中,可以定义立即执行的匿名函数:

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

你能在 PHP 中做类似的事情吗?

20411 次浏览

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

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";
});


?>

Not executed inmediately, but close to ;)

<?php


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


?>

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

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
(new ReflectionFunction(function() {
// body function
}))->invoke();

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

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)

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.