Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an anonymous function return itself?

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

like image 803
Blackbam Avatar asked Oct 29 '18 14:10

Blackbam


People also ask

Can a function return itself?

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.

What is the use of an anonymous function?

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.

Can you assign an anonymous function to a variable and pass it as an argument to another function?

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.


2 Answers

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

like image 171
Alexandre Elshobokshy Avatar answered Sep 21 '22 00:09

Alexandre Elshobokshy


[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';
    })()
);
like image 27
IMSoP Avatar answered Sep 19 '22 00:09

IMSoP