Home » Php » php – Can an anonymous function return itself?

php – Can an anonymous function return itself?

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&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

Answer:

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

Answer:

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