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.
But the PHP documentation explicitly says the first parameter to call_user_func() should be a string
No it doesn't.
mixed call_user_func ( callable $callback [, mixed $parameter [, mixed $... ]] )
The first parameter is of type callable, so your code is perfectly valid :)
Your solution is appropriate. The first argument to call_user_func should be a callable, a type which includes closures.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With