PHP Variable variables

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.

This entry was posted in Articles and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

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