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
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
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.
Not elegantly... BUT YOU COULD FAKE IT!
$a = 10 //becomes $a = '0a'; $$a = 10;
Addendum: Only do this if you are
Bit late to the game here, but Mach 13 has an interesting solution: How to get a variable name as a string in PHP
You could use eval:
function debug($variablename)
{
echo ($variablename . ":<br/>");
eval("global $". $variablename . ";");
eval("var_dump($" . $variablename . ");");
}
Usage: debug("myvar")
not debug($myvar)
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)