Tim Keller

Web, IT, Telecoms, Development, Networks, Photography, Life.

PHP Variable variables

without comments

A seldom used, but incredibly useful, aspect of PHP is the ability to reference variables by name, based on the contents of a variable. Don’t worry if that sentence didn’t make sense to you. Let’s see an example:

$a = "hello";       // $a is "hello"
$$a = "world";    // Now $hello = "world"
echo "$a ${$a}"   // outputs "hello world"
echo "$a $hello" // also ouptuts "hello world"

This is useful in the situation that you need to access an object class variable at runtime. Let’s say we have three class variables:

$this->cycle_1_mark
$this->cycle_2_mark
$this->cycle_3_mark

At runtime, we have a variable $semester which holds the current semester. To it access it, we do something like:

$myObject = new Object();
echo $myObject->{"cycle_$semester_mark"};  // outputs the value for the substituted class variable

More on PHP.net:Variable Variables.

Written by Tim Keller

May 5th, 2010 at 6:57 pm

Posted in Uncategorized

Leave a Reply