Can an anonymous function return itself?

Viewed 535

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

3 Answers

[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';
    })()
);

An anonymous function cannot return a reference to itself as far as I know, and there is no built-in PHP function that returns a reference to itself as far as I know, so that would leave an invokable class. That could work:

new class{function __invoke(){return $this;}}

answers-to-returntrue.win-with-explanations

Related