php - 从匿名子函数中获取父函数的名称
问题描述
我想知道是否可以从嵌套函数中获取函数的名称。我已经尝试过,__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;
}
解决方案
这里不需要额外的变量,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();
推荐阅读
- tensorflow - ValueError:发现样本数量不一致的输入变量:[84, 5]
- assembly - 尝试用循环绘制垂直形状
- php - 在 PHP 表单中,字符串输入在提交后被转换为 0
- python - numpy 作者如何决定是否将函数放入 numpy.* 与 numpy.ndarray.* 中?
- go - 如何在 Visual Studio 代码中允许“供应商”文件夹支持
- html - Css Position:sticky 仅在 MOBILE 中不起作用
- python - 如何从 .gitlab-ci.yml 文件中提取单个管道名称?
- php - 如果脚本被注入到私有页面中,XSS 错误仍然很危险吗?
- python - Pandas 列的字典并选择正确的值
- ansible - ansible 检查文件名与不同的字符串大小写,我可以实现 if/else 吗?