phpjavascriptfunction

How do I immediately execute an anonymous function in PHP?


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

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

Can you do something like that in PHP?


Solution

  • 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'; })();