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

20,380

Solution 1

You can do it by converting the variable to a key/value set before passing it to the function.

function varName($theVar) {  
   $variableName = key($theVar);  
   $variableValue = $theVar[$variableName];  
   echo ('The name of the variable used in the function call was '.$variableName.'<br />');  
   echo ('The value of the variable used in the function call was '.$variableValue.'<br />');  
}
$myVar = 'abc';
varName(compact('myVar'));

Though I don't recommend creating a reference to a nameless variable, function varName(&$theVar) works too.

Since compact() takes the variable name as a string rather than the actual variable, iterating over a list of variable names should be easy.

As to why you would want to do this -- don't ask me but it seems like a lot of people ask the question so here's my solution.

Solution 2

I know I'm answering a 4 year old question but what the hell...

compact() might help you is your friend here!

I made a similar function to quickly dump out info on a few chosen variables into a log for debugging errors and it goes something like this:

function vlog() {
    $args = func_get_args();
    foreach ($args as $arg) {
        global ${$arg};
    }
    return json_encode(compact($args));
}

I found JSON to be the cleanest and most readable form for these dumps for my logs but you could also use something like print_r() or var_export().

This is how I use it:

$foo = 'Elvis';
$bar = 42;
$obj = new SomeFancyObject();

log('Something went wrong! vars='.vlog('foo', 'bar', 'obj'));

And this would print out like this to the logs:

Something went wrong! vars={"foo":"Elvis","bar":42,"obj":{"nestedProperty1":1, "nestedProperty2":"etc."}}

Word of warning though: This will only work for variables declared in the global scope (so not inside functions or classes. In there you need to evoke compact() directly so it has access to that scope, but that's not really that big of a deal since this vlog() is basically just a shortcut for json_encode(compact('foo', 'bar', 'obj')), saving me 16 keystrokes each time I need it.

Solution 3

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

Solution 4

Nope, not possible. Sorry.

Solution 5

No, the closer you will get is with get_defined_vars().

EDIT: I was wrong, after reading the user comments on get_defined_vars() it's possible with a little hack:

function ev($variable){
    foreach($GLOBALS as $key => $value){
        if($variable===$value){
            echo '<p>$'.$key.' - '.$value.'</p>';
        }
    }
}

$lol = 123;

ev($lol); // $lol - 123

Only works for unique variable contents though.

Share:
20,380

Related videos on Youtube

Petruza
Author by

Petruza

General software engineer, golang advocate, also typescript, C, C++, GDScript dev. Interested in emulation, video games, image processing, machine learning, computer vision, natural language processing, web scraping.

Updated on July 09, 2022

Comments

  • Petruza
    Petruza almost 2 years

    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 the programmer writes a call to the function, they already know the variable's name, so they could write something like:

    debug( $myvar, 'myvar' );

    But I want it to be quick and easy to write, just the function name, the variable, and voilà !

    debug( $myvar ); // quicker and easier :)
    • outis
      outis over 13 years
    • Sasa1234
      Sasa1234 about 8 years
      Why we need to get a name of a variable? Which type of situation?
    • Petruza
      Petruza about 8 years
      @Sasa1234 Exactly the type of situation I described on the question.
    • fcrick
      fcrick over 7 years
      Referring to the variable only is more maintainable in this situation, as well, as using an IDE to rename the variable, for example, would break the earlier version, but not the later one, as the names would no longer match.
    • miken32
      miken32 almost 6 years
    • Petruza
      Petruza almost 6 years
      @miken32 After all these years?
    • miken32
      miken32 almost 6 years
      @Petruza always
  • chaos
    chaos over 14 years
    Unique variable contents that are globals. Lovely false positive rate there.
  • chaos
    chaos over 14 years
    It's not completely ridiculous to think that such a capability might be possible, but it would require ReflectionParameter having tracking for the source variable name if one exists (presumably it would be null when an rvalue is passed), and it doesn't.
  • nickf
    nickf over 14 years
    not only does this not work (your function won't have the right scope), but there's a much better way to do the same thing with Variable Variables: $$variablename
  • Waggers
    Waggers over 14 years
    I've changed the function to account for the loss of scope. I'm not to familiar with variable variables but will take your word for it!
  • Alix Axel
    Alix Axel over 14 years
    No need to eval, just use variable variables.
  • Alix Axel
    Alix Axel over 14 years
    Indeed, better than nothing though. =\
  • Petruza
    Petruza over 14 years
    Yes, I was like 99% sure it wasn't possible before making the question, but there's always someone on SO that knows more than you so... And thinking about how loosely typed and un-strict PHP is, this woudn't be such a crazy feature. Anyway, it's not that useful, so me: stop dreaming.
  • Petruza
    Petruza over 14 years
    yes, but this solution, as well as eyze's work only for globals. But thanks anyway!
  • chaos
    chaos over 14 years
    Aww, don't be sad, little Lego person. Your two-argument debug() isn't that bad.
  • nickf
    nickf over 14 years
    debug("a; mysql_query('DELETE FROM users WHERE 1');")
  • Petruza
    Petruza over 13 years
    Thanks. I'm a Playmobil by the way.
  • Petruza
    Petruza over 13 years
    Thanks, it's a good one. As to why I would do this, it's in the original post: I want to make a debug function that gets a variable and prints a var_dump and the variable name. Although now that I see, it requires calling compact(), but anyway it's already proven that there's no solution like the one I was looking for.
  • rjha94
    rjha94 over 12 years
    Rudu, I do not think Mach 13 solution would count as a solution to what has been asked here. @see also marc.info/?l=php-general&m=112174126218786&w=2
  • Rudu
    Rudu over 12 years
    @rjha94 - You're two years late mate and did you read the article? Rasmus' post is linked and yet there's a solution both there, and in the accepted answer (by @EngineerGreg) above.
  • adilbo
    adilbo about 4 years
    Yes, it’s possible, take a look over her: stackoverflow.com/a/36921487/5201919
  • Wiktor Stribiżew
    Wiktor Stribiżew over 2 years
    The link is dead, please update.