109

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

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

Can you do something like that in PHP?

1
  • 2
    I don't have php 5.3 on my hands to try out, but how does call_user_func(function(){/* stuff */}) do?
    – Jasper
    Aug 25, 2010 at 20:19

9 Answers 9

140

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'; })();
9
  • 12
    Unless (or, until) function call chaining gets introduced, this would be my suggestion as well.
    – salathe
    Aug 25, 2010 at 18:15
  • 2
    @Gordon: php 5.4 still nothing ?
    – dynamic
    Oct 30, 2012 at 21:03
  • @yes123 nope. still have to use call_user_func
    – Gordon
    Oct 30, 2012 at 22:41
  • 2
    @BennettMcElwee let's put it this way: even if this performs somewhat slower than the define-assign-call alternative, the likelihood of this posing a significant bottleneck in your application is very low. when in doubt profile your app under real world conditions.
    – Gordon
    Jun 21, 2013 at 5:44
  • Thanks @Gordon, that's what I thought. I got the impression that salathe and yes123 weren't happy with this method, and I wondered why. Seems perfectly fine to me. Jun 21, 2013 at 10:47
33

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
0
15

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

0
14

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

?>
10
  • 1
    I want an immediately executing function, because the function I am defining is one which SHOULDN'T be called more than once in normal execution. The problem with defining a named function, run(), like you have, is that anyone else who sees the code may think that they can call run() too in some other part of the code. The immediately-executing function makes it clear that this code should not be run twice. Sep 18, 2013 at 9:05
  • 3
    They cannot call run on your function in some other part of the code because there is no handle to your function existing after the line which immediately executes it.
    – Pacerier
    Sep 18, 2013 at 13:31
  • 3
    @DanielHoward The point of run() is to immediately execute the unnamed function passed to it. Same as call_user_func(), only no parameters are passed.
    – Cypher
    Feb 7, 2014 at 23:02
  • 1
    @JordanLev, It has a simpler implementation (just one line: $f();) and might be faster if the engine you use does not optimize for the special case where call_user_func has only one function argument. This is because call_user_func supports passing multiple parameters and it's first argument supports either a string as an argument or a function. That said, if call_user_func is much readable, I'd not use run unless the code is located somewhere at the bottom of the pyramind.
    – Pacerier
    Sep 2, 2015 at 8:30
  • 1
    @JordanLev, "simpler implementation" refers to the comparison between the code inside the functions run and call_user_func. call_user_func has an inherent disadvantage when compared to run because run does only one thing, whereas call_user_func supports additional features in addition to doing what run does. You can try a quick loop test (e.g.) to see which is faster on your engine.
    – Pacerier
    Sep 3, 2015 at 4:33
6
(new ReflectionFunction(function() {
 // body function
}))->invoke();
1
  • 6
    can you provide more detail? maybe add an explanation?
    – MoralCode
    Feb 5, 2016 at 21:53
4

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)
0

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.
3
  • What possible value could there be to doing this instead of defining an anonymous function? Sure it's possible to do, but why?
    – miken32
    May 21, 2021 at 16:20
  • 1
    @miken32 Because maybe you want to execute more complex stuff than returning 'neato'. Having a class construct (anonymous singleton pattern) that will run once will allow for much more 'neato' organisation of your code. Whoever downvoted this answer should seriously question if they're active in the right industry. This answer is not strictly the right one for this question, but it's definitely a solid alternative when more complexity is needed than just a single function. BTW, you can just write (new class(){function __construct(){echo 'neato';}}); to fire up the class.
    – zmippie
    Jul 25, 2021 at 6:33
  • @miken32 Thanks for the feedback! It can be even cooler when using variables to dynamically call methods on an anonymous class, such as: stackoverflow.com/questions/5451394/call-method-by-string Oct 27, 2021 at 2:30
-1

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();
1
  • 3
    Then why not simply $hack = function(){...}; $hack()?
    – user5147563
    Jul 8, 2017 at 18:39
-2

Not executed inmediately, but close to ;)

<?php

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

?>

Not the answer you're looking for? Browse other questions tagged or ask your own question.