how do I use variable variables.

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
sos
Forum Newbie
Posts: 7
Joined: Thu Jan 02, 2003 9:35 pm

how do I use variable variables.

Post by sos »

What I am dying to know is some of the ways that I can use variable variables?

I already can grasp the idea on how they work, but I can not understand there usefulness and how to use them.

a variable variables definition is: a variable variable takes the value of a variable and treats that as the name of a variable. Good I understand all that not a problem for me.

Code: Select all

<?php 
$test="This is test"; 
$b="test"; 
$a=$&#123;$b&#125;; 

echo $a; 
?> 

output "This is test"
I can see how this prints "This is test" to the browser thats not a problem for me.

The problem for comes when I try to think of a reason to use a variable
variable, so if anyone can show me an easy to follow example of a variable variable in use, that will I hope help clarify things in my mind.

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

Post by volka »

let me ask a question in return: why not?
Of course there's always a way to code without variable variables, other languages serve very well without this feature. But at some occasions you might find them very handy, very easy ...and php is coding the easy way ;)
One example might be that data is delivered from outside and there's nothing you can do about the format, handling is always the same but the naming convention is something like premature (yeah, depending on other people's work can be nasty :D ). Can't think of a better example right now....
User avatar
hob_goblin
Forum Regular
Posts: 978
Joined: Sun Apr 28, 2002 9:53 pm
Contact:

Post by hob_goblin »

sos
Forum Newbie
Posts: 7
Joined: Thu Jan 02, 2003 9:35 pm

I think I am seeing something.

Post by sos »

You might want to use a variable variable to capture and store a value of another variable that you might want to find out some more information on.

And then maybe after comparing it to something or running some sort of logical tests on the new variable you can call something else in the script to be done.

The Idea is a little murky in my head, but I think I am seeing something but the detail is still not there. I hope things start to become clearer the more I continue to look at php.

Thanks for the support.

Code: Select all

<?
$blue = "blue";
$red = "blue";
$a = "red";
if ($a == $&#123;$a&#125;) &#123;
	echo "The value of \$red is red!"."<P>";
	&#125; else if ($blue == $&#123;$a&#125;) &#123;
	echo "The value of \$red is blue!"."<p>";
	&#125; else &#123;
	echo "I am confused!";
	&#125;
?>
Post Reply