Can an anonymous function return itself?
You can create an anonymous function that returns a reference to itself:
foo($x=function()use(&$x){return$x;})
http://sandbox.onlinephpfunctions.com/code/743f72c298e81e70f13dc0892894911adfb1b072
[Whitespace is for readability only; all of these should work on one line if required.]
As a variation on Islam Elshobokshy's answer, you could use a (super-)global variable instead of a use
statement to give the function access to itself:
foo(
$GLOBALS['x'] = function() {
return $GLOBALS['x'];
}
);
Or you could let the function find itself in the call stack using debug_backtrace:
foo(
function() {
$backtrace = debug_backtrace();
return $backtrace[1]['args'][0];
}
)
Inspired by a comment from Spudley about returning a function name, you can actually declare a function within the scope allowed by wrapping it in an IIFE:
foo(
(function(){
function f(){ return 'f'; }
return 'f';
})()
);