1

I was wondering if I can get the name of a function from a nested function. I have tried with __FUNCTION__ but the way I am doing it I do not get the expected result, I think it is due to a scope problem. Suppose I have the following:

public function function_1($arguments)
{
     if (is_array($arguments)) {
         return array_map(function ($argument) {
             // Here I would like __FUNCTION__ to return the string functon_1
             // to refer to the name of the parent function.
             return call_user_func_array([$this, __FUNCTION__], [$argument]);
         }, $arguments);
     }

     return $arguments;
}

Thank you very much in advance for any help you can give me.

EDIT 1

For now I have managed to get the expected result as follows:

public function function_1($arguments)
{
     $callback = __FUNCTION__;

     if (is_array($arguments)) {
         return array_map(function ($argument) use ($callback) {
             // Here I would like __FUNCTION__ to return the string functon_1
             // to refer to the name of the parent function.
             return call_user_func_array([$this, $callback], [$argument]);
         }, $arguments);
     }

     return $arguments;
}
leo95batista
  • 699
  • 9
  • 27
  • 1
    You could pass the name of the function to the anonymous function using [use](https://stackoverflow.com/questions/6320521/use-keyword-in-functions-php) – Definitely not Rafal Apr 07 '21 at 05:25
  • Hi @DefinitelynotRafal! Thank you very much for your answer, I have made an update to my question, see the changes. As you indicate, I can only pass variables. But, I wonder if there is a more elegant way to do what I need. Anyway, thank you very much for the help you give me. – leo95batista Apr 07 '21 at 05:31

1 Answers1

1

You don't need an extra variable here, debug_backtrace can help you to crawl the call stack.

function aaa()
{
    array_map(function ()
    {
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);

        var_dump($backtrace[2]['function']); # 0 - this closure
                                             # 1 - array_map
                                             # 2 - aaa

    }, [1, 2, 3]);
}

aaa();
user1597430
  • 1,138
  • 1
  • 7
  • 14