In some PHP quiz I got the following task - I have to return true
on the following:
function foo($x)
{
return $x === $x();
}
foo(__________ALLOWED_INPUT____________);
Now my idea was to pass an anonymous function which returns itself:
foo(function() { return $this_function; })
However I did not yet figure out a way to do this. Is it possible somehow?
PS: Nice Game (https://returntrue.win/?level=6).
Am I missing something? @SamuelEbert, yes this function returns itself, but also is bloated with functional which is useless for the context of the question and focuses on that additional functional.
An anonymous function is a function that does not have any name associated with it. Normally we use the function keyword before the function name to define a function in JavaScript, however, in anonymous functions in JavaScript, we use only the function keyword without the function name.
They're called anonymous functions because they aren't given a name in the same way as normal functions. Because functions are first-class objects, we can pass a function as an argument in another function and later execute that passed-in function or even return it to be executed later.
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';
})()
);
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