长话短说,我有这样一个场景:
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(),我需要输出为“I was just called from 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/