Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

reflection

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 :)
like image 506
Petruza Avatar asked Aug 13 '09 13:08

Petruza


2 Answers

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.

like image 132
EngineerGreg Avatar answered Sep 28 '22 08:09

EngineerGreg


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.

like image 35
Þórður Matthíasson Avatar answered Sep 28 '22 08:09

Þórður Matthíasson