如何在PHP中以编程方式获取变量/const名称


How to get the variable/const name programatically in PHP?

func(CONST_A)应返回'CONST_A', func($name)应返回$name

如何在PHP中实现这个func ?

这似乎不太可能。

你可以使用反射来确定函数的参数,但是它返回函数期望的变量名,如果你已经在函数内部,你已经知道这些了。

debug_backtrace是窥探调用对象的常用方法,但它返回传入参数的,而不是调用者调用时使用的变量名或常量。

然而,给你的是调用者的文件名和行号,所以你可以打开文件并查找该行并解析出来,但那将是非常愚蠢的,你不应该这样做。我不打算给你这个示例代码,因为它是如此愚蠢,你不应该考虑这样做永远

get_defined_vars的东西是一个hack,并不能保证工作,并且肯定不会工作的常量,因为get_defined_constants可以。

试试这个:

<?php
function getVarConst($var)
{
    if (isset($GLOBALS[$var]) // check if there is a variable by the name of $var
    {
        return $GLOBALS[$var]; // return the variable, as it exists
    }
    else if (defined($var)) // the variable didn't exist, check if there's a constant called $var
    {
        return constant($var); // return the constant, as it exists
    }
    else
    {
        return false; // return false, as neither a constant nor a variable by the name of $var exists
    }
}
?>

这是不可能的

您确实想要以下内容,对吗?

 define('CONST_A', 'THIS COULD BE ANYTHING');
 $name = 'who cares';
 func(CONST_A); //returns 'CONST_A'
 func($name);   //returns '$name'

函数不能知道。

我认为像Charles描述的那样阅读源代码可以让你得到这个,但是为什么呢?