PHP variable variables
Over the coming weeks I’m going to be writing some posts on object orientated programming in PHP5, but to get us started there are a few techniques that we need to know, so today I’m going to be looking at variable variables.
Naming conventions are really important when it comes to variable names in programming and one way we can get around this is by using the value of the variable string as the variable name. to explain this better i’ve put together the following code.
$a = 'Ashley';
$b = 'Papermashup';
$c = 'John';
$d = 'Mark';
$e = 'Luke';
$values = array('a', 'c', 'd');
foreach($values as $seat){
echo $$seat .'<br />';
}
Lets start by looking at the end of the code and more specifically the echo statement. Notice how there are two $ signs, this is because we are saying take the value of $seat and use it as the variable name and we do that by using $$. The rest of the code is pretty self explanatory, a simple array which we loop through to return the values of a, c and d.
Variable variables are a good way of trimming down unnecessary code.




I didn’t get it… Why did you use $$ instead of $var? Could you explain a little more?
I gotta say, I’m new to OO PHP so I really appreciate your post series on this topic.
Thanks.
@hassan
inside the loop $seat will be first “a”, then “c” and at last $set will be “d”.
but we do not want to write:
a
c
d
but we want to output the content of the variables $a $c and $d:
Ashley
John
Mark
so $$seat calls the variable that is named like the content of $seat, at first $a, then $c, then $d.
sorry for my bad english
Thanks Laszlo, keep up the good working.
Well I didn’t know that, thank you :p
Leave a comment...
Connect
Latest Poll
Recent Posts