PHP variable variables

7 April 2009| 4 Comments| Print

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.

demo


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

4 Comments

  • Hassan

    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.

  • Laszlo Korte

    @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

  • OÄŸuz ÇELİKDEMİR

    Thanks Laszlo, keep up the good working.

  • Ben

    Well I didn’t know that, thank you :p

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here