首页 > 解决方案 > 从匿名子函数中获取父函数的名称

问题描述

我想知道是否可以从嵌套函数中获取函数的名称。我已经尝试过,__FUNCTION__但是我这样做的方式没有得到预期的结果,我认为这是由于范围问题。假设我有以下内容:

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;
}

非常感谢您提前为我提供的任何帮助。

编辑 1

现在我已经设法得到预期的结果如下:

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;
}

标签: php

解决方案


这里不需要额外的变量,debug_backtrace可以帮你爬取调用栈。

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();

推荐阅读