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

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

    Here's my solution based on Jeremy Ruten

    class DebugHelper {
    
        function printVarNames($systemDefinedVars, $varNames) {
            foreach ($systemDefinedVars as $var=>$value) {
                if (in_array($var, $varNames )) {
                    var_dump($var);
                    var_dump($value);
                }
            }
        }
    }
    

    using it

    DebugHelper::printVarNames(
        $systemDefinedVars = get_defined_vars(),
        $varNames=array('yourVar00', 'yourVar01')
    );
    
    0 讨论(0)
  • 2020-11-22 02:05

    You could use compact() to achieve this.

    $FooBar = "a string";
    
    $newArray = compact('FooBar');
    

    This would create an associative array with the variable name as the key. You could then loop through the array using the key name where you needed it.

    foreach($newarray as $key => $value) {
        echo $key;
    }
    
    0 讨论(0)
  • 2020-11-22 02:05

    why we have to use globals to get variable name... we can use simply like below.

        $variableName = "ajaxmint";
    
        echo getVarName('$variableName');
    
        function getVarName($name) {
            return str_replace('$','',$name);
        }
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 02:08

    No-one seems to have mentioned the fundamental reasons why this is a) hard and b) unwise:

    • A "variable" is just a symbol pointing at something else. In PHP, it internally points to something called a "zval", which can actually be used for multiple variables simultaneously, either because they have the same value (PHP implements something called "copy-on-write" so that $foo = $bar doesn't need to allocate extra memory straight away) or because they have been assigned (or passed to a function) by reference (e.g. $foo =& $bar). So a zval has no name.
    • When you pass a parameter to a function you are creating a new variable (even if it's a reference). You could pass something anonymous, like "hello", but once inside your function, it's whatever variable you name it as. This is fairly fundamental to code separation: if a function relied on what a variable used to be called, it would be more like a goto than a properly separate function.
    • Global variables are generally considered a bad idea. A lot of the examples here assume that the variable you want to "reflect" can be found in $GLOBALS, but this will only be true if you've structured your code badly and variables aren't scoped to some function or object.
    • Variable names are there to help programmers read their code. Renaming variables to better suit their purpose is a very common refactoring practice, and the whole point is that it doesn't make any difference.

    Now, I understand the desire for this for debugging (although some of the proposed usages go far beyond that), but as a generalised solution it's not actually as helpful as you might think: if your debug function says your variable is called "$file", that could still be any one of dozens of "$file" variables in your code, or a variable which you have called "$filename" but are passing to a function whose parameter is called "$file".

    A far more useful piece of information is where in your code the debug function was called from. Since you can quickly find this in your editor, you can see which variable you were outputting for yourself, and can even pass whole expressions into it in one go (e.g. debug('$foo + $bar = ' . ($foo + $bar))).

    For that, you can use this snippet at the top of your debug function:

    $backtrace = debug_backtrace();
    echo '# Debug function called from ' . $backtrace[0]['file'] . ' at line ' . $backtrace[0]['line'];
    
    0 讨论(0)
  • 2020-11-22 02:08

    I have this:

      debug_echo(array('$query'=>$query, '$nrUsers'=>$nrUsers, '$hdr'=>$hdr));
    

    I would prefer this:

      debug_echo($query, $nrUsers, $hdr);
    

    The existing function displays a yellow box with a red outline and shows each variable by name and value. The array solution works but is a little convoluted to type when it is needed.

    That's my use case and yes, it does have to do with debugging. I agree with those who question its use otherwise.

    0 讨论(0)
提交回复
热议问题