伪造闭包的函数名称


Faking a closure's function name

省略一个长篇大论,我有一个这样的场景:

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;
}

在不更改 doSomething() 中的任何内容的情况下,我唯一能想到的就是使用 eval()

function __call($method, $args)
{
    eval("
         function {$method}('$self) {
              '$self->doSomething();
         }
         {$method}('$this);
    ");
}