How do I immediately execute an anonymous function in PHP?

前端 未结 9 977
离开以前
离开以前 2020-11-27 03:29

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

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

Can you do somethin

相关标签:
9条回答
  • 2020-11-27 03:43

    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.
    
    0 讨论(0)
  • 2020-11-27 03:46

    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 讨论(0)
  • 2020-11-27 03:47

    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'; });
    
    0 讨论(0)
  • 2020-11-27 03:48
    (new ReflectionFunction(function() {
     // body function
    }))->invoke();
    
    0 讨论(0)
  • 2020-11-27 03:48

    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();
    
    0 讨论(0)
  • 2020-11-27 03:50

    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.

    https://3v4l.org/06EL3

    0 讨论(0)
提交回复
热议问题