What’s the suggested way to execute an anonymous function in PHP similar to how Javascript provides this possibility?
Javascript:
(function(){ console.log('Hello!'); })();
Trying the same in PHP yields a syntax error for the parameters opening bracket. I’ve found a way around this problem by “mis-using” call_user_func():
PHP:
call_user_func(function(){ echo "Hello!"; });
But the PHP documentation (update: the German version of the docs) explicitly says the first parameter to call_user_func() should be a string… So I’m not sure if my solution is supposed to work correct (however, it does for the moment).
The purpose behind this solution – similar to the reason why you would do it the same way in JavaScript – is to not pollute the global namespace for some added functionality. This script is auto-prepended for all scripts on the whole server and should be hidden wrt global namespace and global scope. It’s not meant to be invisible – just keep symbols out of the namespace.
No it doesn’t.
The first parameter is of type
callable, so your code is perfectly valid 🙂