Tower Tower - 6 months ago 23
PHP Question

How to call the current anonymous function in PHP?

I have an anonymous function which is supposed to call itself. However, I have no variable or function name at hand, so I was hoping to find a function that could do return "this" in context of functions. Is there such a thing?

Here's an example:

$f = function() use($bar, $foo) {
// call this function again.
};


Calling like this:

call_user_func(__FUNCTION__);


Leads to this:


Warning: call_user_func() expects parameter 1 to be a valid callback,
function '{closure}' not found or invalid function name


If I try to put $f in the use-list, then it says the variable is not defined (because it is not yet).

Answer

__FUNCTION__ cannot be used in anonymous functions

Pass the variable holding the anonymous function as a reference in the 'use' clause....

$f = function() use($bar, $foo, &$f) {
   $f();
};

Tip of the hat to this answer.