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

前端 未结 24 1427
南旧
南旧 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:57

    Lucas on PHP.net provided a reliable way to check if a variable exists. In his example, he iterates through a copy of the global variable array (or a scoped array) of variables, changes the value to a randomly generated value, and checks for the generated value in the copied array.

    function variable_name( &$var, $scope=false, $prefix='UNIQUE', $suffix='VARIABLE' ){
        if($scope) {
            $vals = $scope;
        } else {
            $vals = $GLOBALS;
        }
        $old = $var;
        $var = $new = $prefix.rand().$suffix;
        $vname = FALSE;
        foreach($vals as $key => $val) {
            if($val === $new) $vname = $key;
        }
        $var = $old;
        return $vname;
    }
    

    Then try:

    $a = 'asdf';
    $b = 'asdf';
    $c = FALSE;
    $d = FALSE;
    
    echo variable_name($a); // a
    echo variable_name($b); // b
    echo variable_name($c); // c
    echo variable_name($d); // d
    

    Be sure to check his post on PHP.net: http://php.net/manual/en/language.variables.php

提交回复
热议问题