Php 从匿名子函数获取父函数的名称
我想知道是否可以从嵌套函数中获取函数名。我试过使用Php 从匿名子函数获取父函数的名称,php,Php,我想知道是否可以从嵌套函数中获取函数名。我试过使用\uuuuu函数\uuuuu,但我这样做并没有得到预期的结果,我认为这是由于范围问题。假设我有以下几点: public function function_1($arguments) { if (is_array($arguments)) { return array_map(function ($argument) { // Here I would like __FUNCTION__ to
\uuuuu函数\uuuuu
,但我这样做并没有得到预期的结果,我认为这是由于范围问题。假设我有以下几点:
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;
}
这里不需要额外的变量,
debug\u 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();
您可以使用Hi@DefinitelynotRafal将函数名传递给匿名函数!非常感谢您的回答,我已经更新了我的问题,请参阅更改。正如您所指出的,我只能传递变量。但是,我想知道是否有一种更优雅的方式来满足我的需求。无论如何,非常感谢你给我的帮助。