Papermashup

Subscribe


Tweets


"RT @bethgordon: .@Tesco Please rethink archaic 'Approved by Mums'. Pretty sure it's not just mothers who make childcare decisions. https://…"

@ashleyford 3 hours ago

"Is there ever a time that @DFS doesn't have a sale on?"

@ashleyford 4 days ago

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

PHP variable variables

AshleyAshley

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 .'
'; }

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

Designer and web developer, Co-founder and Technical Director at Harkable.com. Previously I worked at Spotify, MySpace and InMobi. Contact me - ashley[at]papermashup.com

Comments 4
  • Ben
    Posted on

    Ben Ben

    Reply Author

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


  • OÄŸuz ÇELÄ°KDEMÄ°R
    Posted on

    Oğuz ÇELİKDEMİR Oğuz ÇELİKDEMİR

    Reply Author

    Thanks Laszlo, keep up the good working.


  • Laszlo Korte
    Posted on

    Laszlo Korte Laszlo Korte

    Reply Author

    @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


  • Hassan
    Posted on

    Hassan Hassan

    Reply Author

    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.