How to print variable name?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

How to print variable name?

Post by scorphus »

Hello dear mates,

Take a look to this C++ code I use for debug purposes:

Code: Select all

#include <iostream>
using namespace std;

#define print_var(var) cout << #var << ": " << var << endl

int main (void) &#123;
	int foo = 123;
	print_var(foo);
	return 0;
&#125;
and it's output:

Code: Select all

foo: 123
As you can see, #var prints the name of the variable. How would you do this in PHP?

Thanks,
Scorphus.
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

Code: Select all

<?php
function print_var($varname)
{
	global ${$varname};
	echo $varname, ': ', ${$varname};
}

$foo = (int)123;
print_var('foo'); 
?>
not exactly as your c code since you have to import the variable from global namespace (won't work within functions)
Post Reply