Is there a way to get the name of a variable? PHP - Reflection
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.
Related videos on Youtube
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, 2022Comments
-
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 over 13 yearspossible duplicate of How to get a variable name as a string in PHP?
-
Sasa1234 about 8 yearsWhy we need to get a name of a variable? Which type of situation?
-
Petruza about 8 years@Sasa1234 Exactly the type of situation I described on the question.
-
fcrick over 7 yearsReferring 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 almost 6 yearsPossible duplicate of How to get a variable name as a string in PHP?
-
Petruza almost 6 years@miken32 After all these years?
-
miken32 almost 6 years@Petruza always
-
-
chaos over 14 yearsUnique variable contents that are globals. Lovely false positive rate there.
-
chaos over 14 yearsIt'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 over 14 yearsnot 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 over 14 yearsI'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 over 14 yearsNo need to eval, just use variable variables.
-
Alix Axel over 14 yearsIndeed, better than nothing though. =\
-
Petruza over 14 yearsYes, 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 over 14 yearsyes, but this solution, as well as eyze's work only for globals. But thanks anyway!
-
chaos over 14 yearsAww, don't be sad, little Lego person. Your two-argument
debug()
isn't that bad. -
nickf over 14 yearsdebug("a; mysql_query('DELETE FROM
users
WHERE 1');") -
Petruza over 13 yearsThanks. I'm a Playmobil by the way.
-
Petruza over 13 yearsThanks, 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 over 12 yearsRudu, 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 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 about 4 yearsYes, it’s possible, take a look over her: stackoverflow.com/a/36921487/5201919
-
Wiktor Stribiżew over 2 yearsThe link is dead, please update.