Is there a way to get the name of a variable? PHP - Reflection

前端 未结 11 588
旧巷少年郎
旧巷少年郎 2020-12-15 08:50

I know this is not exactly reflection, but kind of. I want to make a debug function that gets a variable and prints a var_dump and the variable name.

Of course, when

相关标签:
11条回答
  • 2020-12-15 09:04

    This is late post but I think it is possible now using compact method

    so the code would be

    $a=1;
    $b=2;
    $c=3
    
    var_dump(compact('a','b','c'));
    

    the output would be

    array (size=3)
    'a' => int 1
    'b' => int 2
    'c' => int 3
    

    where variable name a, b and c are the key

    Hope this helps

    0 讨论(0)
  • 2020-12-15 09:10

    i've had the same thought before, but if you really think about it, you'll see why this is impossible... presumably your debug function will defined like this: function debug($someVar) { } and there's no way for it to know the original variable was called $myvar.

    The absolute best you could do would be to look at something like get_defined_vars() or $_GLOBALS (if it were a global for some reason) and loop through that to find something which matches the value of your variable. This is a very hacky and not very reliable method though. Your original method is the most efficient way.

    0 讨论(0)
  • 2020-12-15 09:11

    Not elegantly... BUT YOU COULD FAKE IT!

    • 1) Drink enough to convince yourself this is a good idea (it'll take a lot)
    • 2) Replace all your variables with variable variables:
    $a = 10
    //becomes
    $a = '0a';
    $$a = 10;
    
    • 3) Reference $$a in all your code.
    • 4) When you need to print the variable, print $a and strip out the leading 0.

    Addendum: Only do this if you are

    • Never showing this code to anyone
    • Never need to change or maintain this code
    • Are crazy
    • Not doing this for a job
    • Look, just never do this, it is a joke
    0 讨论(0)
  • 2020-12-15 09:15

    Bit late to the game here, but Mach 13 has an interesting solution: How to get a variable name as a string in PHP

    0 讨论(0)
  • 2020-12-15 09:16

    You could use eval:

    function debug($variablename)
    {
      echo ($variablename . ":<br/>");
      eval("global $". $variablename . ";");
      eval("var_dump($" . $variablename . ");");
    }
    

    Usage: debug("myvar") not debug($myvar)

    0 讨论(0)
  • 2020-12-15 09:20

    I believe Alix and nickf are suggesting this:

    function debug($variablename)
    {
      echo ($variablename . ":<br/>");
      global $$variablename; // enable scope
      var_dump($$variablename);
    }
    

    I have tested it and it seems to work just as well as Wagger's code (Thanks Wagger: I have tried so many times to write this and the global variable declaration was my stumbling block)

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