且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在PHP中以字符串形式获取变量名?

更新时间:2023-02-18 20:51:00

您可以使用 get_defined_vars()查找具有与您要查找的名称相同的值的变量的名称.显然,这并不总是可行的,因为不同的变量通常具有相同的值,但这是我想到的唯一方法.

You could use get_defined_vars() to find the name of a variable that has the same value as the one you're trying to find the name of. Obviously this will not always work, since different variables often have the same values, but it's the only way I can think of to do this.

get_defined_vars()似乎不能正常工作,它返回'var',因为在函数本身中使用了$ var. $ GLOBALS似乎可以正常工作,因此我将其更改为该值.

get_defined_vars() doesn't seem to be working correctly, it returns 'var' because $var is used in the function itself. $GLOBALS seems to work so I've changed it to that.

function print_var_name($var) {
    foreach($GLOBALS as $var_name => $value) {
        if ($value === $var) {
            return $var_name;
        }
    }

    return false;
}

显然,在PHP中没有很好的方法来完成此操作,这可能是因为您不必这样做.可能有更好的方法来做您想做的事情.

to be clear, there is no good way to do this in PHP, which is probably because you shouldn't have to do it. There are probably better ways of doing what you're trying to do.