PHP Variable Varibles

Variable variables is the special features of PHP in PHP. It supports to store name of a variable into a variable. It is used to change the variable name dynamically.

Accessing Variables

Variable Variables are start with double dolor($$) sign. It can be used in tree like access, {variable variables name} -> {variable name} -> {variable value}. For example,

$language = "PHP";
$category = "language";
echo $$category;

The $$category is the variable variable in this example. PHP will execute this with the steps, $$category -> $ { $category } -> $language -> PHP.

Accessing Class Properties using Variable Variables

We have an example to access class properties using PHP variable variables.

class College {
var $name = "Arts and Science international";
var $category = "Arts";
}
$objCollege = new College();
$collegeName = "name";
echo $objCollege->$collegeName . "<br/>";

php_variable_variables

Accessing Array Values

We can use PHP variavle variables in arrays. Some times we require to separate variable variables with curly braces to avoid confusions. We have examples to see what will happen if dont use curly braces in PHP variable variables.

$movies = array("Django","Life of Pi");
$entertainment = "movies";
echo $$entertainment[0];

${$entertainment[0]} will return $m which is not found and cause undefined variable error as,

Notice: Undefined variable: m in ..\variable_variables.php on line 4

To resolve this error, we need to change the code as,

$movies = array("Django","Life of Pi");
$entertainment = "movies";
echo ${$entertainment}[0]; // output: Django

This is an example to access class property containing array, using variable variables with curly braces,

class College {
var $name = "Arts and Science international";
var $category = "Arts";
var $u = "Uncategorized";
var $ugCourses = array("B.A","B.Com","B.Sc");
}
$objCollege = new College();
$courses = "ugCourses";
//Output: Uncategorized
echo $objCollege->$courses[0] . "<br/>";
//Output: B.A
echo $objCollege->{$courses}[0] . "<br/>";

This PHP code tutorial was published on June 13, 2013.

↑ Back to Top