Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute purely anonymous function in PHP

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.

like image 991
hurikhan77 Avatar asked Mar 27 '26 23:03

hurikhan77


2 Answers

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 :)

like image 125
Madara's Ghost Avatar answered Mar 29 '26 11:03

Madara's Ghost


Your solution is appropriate. The first argument to call_user_func should be a callable, a type which includes closures.

like image 22
Lusitanian Avatar answered Mar 29 '26 11:03

Lusitanian