撇开长话,我有一个这样的场景:
class Foo {
function doSomething() {
print "I was just called from " . debug_backtrace()[1]['function'];
}
function triggerDoSomething()
{
// This outputs "I was just called from triggerDoSomething".
// This output makes me happy.
$this->doSomething();
}
function __call($method, $args)
{
// This way outputs "I was just called from __call"
// I need it to be "I was just called from " . $method
$this->doSomething();
// This way outputs "I was just called from {closure}"
// Also not what I need.
$c = function() { $this->doSomething() };
$c();
// This causes an infinite loop
$this->$method = function() { $this->doSomething() };
$this->$method();
}
}
在我调用$ foo-> randomFunction()的情况下,我需要将输出读取为“我刚刚从randomFunction中被调用”
是否有办法命名闭包或以其他方式解决此问题?
注意:我无法更改doSomething函数。这是我正在调用的第三方代码的示例,该代码考虑了为执行某项操作而调用该代码的人员的功能名称。
最佳答案
您可以将名称传递给doSomething()
,例如
$this->doSomething($method);
或像
$c = function($func_name) { $this->doSomething($func_name); };
$c($method);
在
doSomething
中,您可以使用该参数。function doSomething($method) {
print "I was just called from " . $method;
}
关于php - 伪造闭包的函数名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27478110/