Monday, July 2, 2018

PHP - how to get a variable's name?

I want to make a little function for debugging purposes, that prints the contents of the variable in a human readable format.



The function is based on the pr() shortcut found in CakePHP framework, i.e. this one:



I have this so far:



function pr($var,$msg){

$pr_debug=true;
if($pr_debug){
echo "
";
if($msg) echo "".$msg.": ";
if(gettype($var)=="array" || gettype($var)=="object" ) echo "
";
print_r($var);
echo "
";
}
}



which prints an optional message ($msg) before the variables content.



But what I want to add, is that if no message is sent, to also print the variable's NAME as such message, so i could get something like this:



$myvar="hello";
pr($myvar);


//should output:




myvar: hello


So inside my function, how can I get the variable's name as a string so I can output it?
i.e. with pr($foo); I need "foo",
$name="biz"; pr($$name); I need "biz",
and so on...



Preferably I want something that would work despite PHP globals configuration or any of that (which by the way I don't understand very well, so any help on GLOBALS stuff would be much appreciated).




Thanks!



Extra: here at stackoverflow, how do i format source code to get PHP formatting and colors? As of now, I simpy used the toolbar in the textarea and chose "code sample"...

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...