8Aug/072
Getting the name of a PHP variable
So I have been wanting to be able to write my very own variable inspector to blow the lid off of var_dump() or print_r(). These functions, while useful, present data in a very archaic way in my opinion. One of the things that irritates me the most is that when I pass a variable to a dump function, I get the variable data returned, but I can never seem to get the variable name that the data is in. Well, I figured since it wasn't available in PHP core, I'd do it myself.
<?php
/**
* Gets the name of the variable to be inspected
*
* @param mixed $var A reference to a variable that is to be inspected
* @return string The string name of the variable, or '[name_not_found]' if not found
*/
function get_var_name(&$var)
{
// Before we start, we need to read the data for the var we are checking
// into a temporary var since we need to pass a reference of the var we
// want the name for. Without this, we would actually be working with
// the original variable, screwing things up royally.
$passed = $var;
// Initialize the variable name return variable
$varName = '';
// Now the fun part... we change the value of the variable whose name we
// want to something random (not the number 4 onion)
$var = 'Scarlett_'.rand().'_Johannson';
// Now we loop through the GLOBAL array and see if we find the GLOBAL array
// key that matches this value
foreach ($GLOBALS as $k => $v) {
// If the value of the GLOBAL is the same as the temp value...
if ($v === $var) {
// Then we snag the GLOBAL key and use it as our var name
$varName = $k;
// And since we have it, we no longer need to loop
break;
}
}
// If there was no name found let the app know
if (empty($varName)) {
$varName = '[name_not_found]';
}
// Now change the value of the variable back to its original state
$var = $passed;
// And finally, return it to the app
return $varName;
}
?>
Using the function is as simple as:
<?php
$stringTest = 'Green and Juicy';
echo 'The variable name that was passed was $' . get_var_name($stringTest);
?>
Example output: The variable name that was passed was $stringTest
Enjoy. And if you want to hate WordPress' handling of code as much as me, feel free.