How do I immediately execute an anonymous function in PHP?
Solution 1:
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:
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:
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:
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