【问题标题】:Get the name of a parent function from an anonymous child function [duplicate]从匿名子函数中获取父函数的名称[重复]
【发布时间】:2021-07-02 21:41:16
【问题描述】:

我想知道是否可以从嵌套函数中获取函数的名称。我试过__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;
}

【问题讨论】:

  • 你可以使用use将函数名传递给匿名函数
  • 嗨@DefinitelynotRafal!非常感谢您的回答,我已经对我的问题进行了更新,请查看更改。正如你所指出的,我只能传递变量。但是,我想知道是否有更优雅的方式来做我需要的事情。不管怎样,非常感谢你给我的帮助。

标签: php


【解决方案1】:

这里不需要额外的变量,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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-11
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-19
    • 2016-06-22
    • 2014-04-09
    相关资源
    最近更新 更多