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

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

    I actually have a valid use case for this.

    I have a function cacheVariable($var) (ok, I have a function cache($key, $value), but I'd like to have a function as mentioned).

    The purpose is to do:

    $colour = 'blue';
    cacheVariable($colour);
    

    ...

    // another session
    

    ...

    $myColour = getCachedVariable('colour');
    

    I have tried with

    function cacheVariable($variable) {
       $key = ${$variable}; // This doesn't help! It only gives 'variable'.
       // do some caching using suitable backend such as apc, memcache or ramdisk
    }
    

    I have also tried with

    function varName(&$var) {
       $definedVariables = get_defined_vars();
       $copyOfDefinedVariables = array();
       foreach ($definedVariables as $variable=>$value) {
          $copyOfDefinedVariables[$variable] = $value;
       }
       $oldVar = $var;
       $var = !$var;
       $difference = array_diff_assoc($definedVariables, $copyOfDefinedVariables);
       $var = $oldVar;
       return key(array_slice($difference, 0, 1, true));
    }
    

    But this fails as well... :(

    Sure, I could continue to do cache('colour', $colour), but I'm lazy, you know... ;)

    So, what I want is a function that gets the ORIGINAL name of a variable, as it was passed to a function. Inside the function there is no way I'm able to know that, as it seems. Passing get_defined_vars() by reference in the second example above helped me (Thanks to Jean-Jacques Guegan for that idea) somewhat. The latter function started working, but it still only kept returning the local variable ('variable', not 'colour').

    I haven't tried yet to use get_func_args() and get_func_arg(), ${}-constructs and key() combined, but I presume it will fail as well.

提交回复
热议问题