获取一个名为函数的名称,相当于CFML的getFunctionCalledName()

时间:2014-09-17 12:23:40

标签: php cfml

以下是我用作基线的CFML代码示例(也在github @ getFunctionCalledName.cfm上):

function f(){
    echo("#getFunctionCalledName()#() called<br>");
}

f();
echo("<hr>");

g = f;
g();

输出:

  

F()叫

     

G()叫

请注意getFunctionCalledName()返回用于调用函数的引用的名称,而不仅仅是函数的名称。

我试图查看PHP中的等价物是否存在。这是我对它的测试(GitHub上的testFunction.php):

我知道__FUNCTION__魔法常数:

function f()
{
    echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
}

f();
echo "<hr>";

$g = "f"; // as someone points out below, this is perhaps not analogous to the g = f in the CFML code above. I dunno how to simply make a new reference to a function (other than via using function expressions instead, which is not the same situation
$g();    

然而,在这两种情况下都会返回f

我已尝试使用类似代码debug_backtrace()(请参阅testDebugBackTrace.php),但也将该函数引用为f

这很好,我理解为什么他们都这样做。但是,我想知道是否有任何PHP等价的getFunctionCalledName()。我赶紧补充说这只是一个探索性的练习:我目前正在从CFML迁移到PHP,当我在我的博客上展示一些东西时,这就出现了。

2 个答案:

答案 0 :(得分:1)

您的代码$g = "f";并未真正将该函数复制到另一个变量,它只是创建了对同一函数的字符串引用。以下内容更类似于您提供的CFML:

$x = function() {
    echo __FUNCTION__;
};

$v = $x;
$v();

上面的代码只输出{closure},因为PHP没有为匿名函数指定正式名称。所以,答案是,不,这在PHP中是不可能的。

答案 1 :(得分:0)

如果没有像runkit扩展这样的东西,我不会想到你在PHP之后可以做些什么。它具有以新名称创建函数副本的功能。我自己没有尝试过,因为我找不到Windows版本的扩展程序。

http://php.net/manual/en/function.runkit-function-copy.php

<?php
function f() {
  echo sprintf("Using __FUNCTION__: %s() called<br>", __FUNCTION__);
}
runkit_function_copy('f', 'g');
f();
g();
?>