How to get a variable name as a string in PHP?

前端 未结 24 1396
南旧
南旧 2020-11-22 01:35

Say i have this PHP code:

$FooBar = \"a string\";

i then need a function like this:

print_var_name($FooBar);
24条回答
  •  抹茶落季
    2020-11-22 02:08

    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.

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

    Edit: 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.

提交回复
热议问题