【发布时间】: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