How do I immediately execute an anonymous function in PHP?

前端 未结 9 1015
离开以前
离开以前 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: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:

     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)
    

提交回复
热议问题