How do I immediately execute an anonymous function in PHP?

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

提交回复
热议问题