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

前端 未结 24 1407
南旧
南旧 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 01:50

    This is the way I did it

    function getVar(&$var) {
        $tmp = $var; // store the variable value
        $var = '_$_%&33xc$%^*7_r4'; // give the variable a new unique value
        $name = array_search($var, $GLOBALS); // search $GLOBALS for that unique value and return the key(variable)
        $var = $tmp; // restore the variable old value
        return $name;
    }
    

    Usage

    $city  = "San Francisco";
    echo getVar($city); // city
    

    Note: some PHP 7 versions will not work properly due to a bug in array_search with $GLOBALS, however all other versions will work.

    See this https://3v4l.org/UMW7V

提交回复
热议问题