php - 伪造一个闭包的函数名

标签 php closures

长话短说,我有这样一个场景:

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/

相关文章:

php - 将 XMLHttpRequest.responseText 存储为变量 :(

php - WordPress PHP Hack 中不允许使用 HTML

JavaScript 闭包

c# - C# 中的闭包 lambda 表达式

javascript - 如果 dom 元素有指向闭包的指针,如果我从页面中删除 dom 元素,这会导致内存泄漏吗?

ios - 与@nonescaping 相比,@escpaing 闭包在内存中的存储方式有何不同

php - 发送带有内嵌图像的电子邮件

php - 在 Like 运算符中使用变量

php - jQuery 函数无法处理使用 Ajax 加载的数据

python - 为什么 Python 类定义不能为自身分配一个闭包变量?