Say i have this PHP code:
$FooBar = \"a string\";
i then need a function like this:
print_var_name($FooBar);
No-one seems to have mentioned the fundamental reasons why this is a) hard and b) unwise:
$foo = $bar
doesn't need to allocate extra memory straight away) or because they have been assigned (or passed to a function) by reference (e.g. $foo =& $bar
). So a zval has no name."hello"
, but once inside your function, it's whatever variable you name it as. This is fairly fundamental to code separation: if a function relied on what a variable used to be called, it would be more like a goto
than a properly separate function.$GLOBALS
, but this will only be true if you've structured your code badly and variables aren't scoped to some function or object.Now, I understand the desire for this for debugging (although some of the proposed usages go far beyond that), but as a generalised solution it's not actually as helpful as you might think: if your debug function says your variable is called "$file", that could still be any one of dozens of "$file" variables in your code, or a variable which you have called "$filename" but are passing to a function whose parameter is called "$file".
A far more useful piece of information is where in your code the debug function was called from. Since you can quickly find this in your editor, you can see which variable you were outputting for yourself, and can even pass whole expressions into it in one go (e.g. debug('$foo + $bar = ' . ($foo + $bar))
).
For that, you can use this snippet at the top of your debug function:
$backtrace = debug_backtrace();
echo '# Debug function called from ' . $backtrace[0]['file'] . ' at line ' . $backtrace[0]['line'];