PHP Variable Varibles

Last modified on February 25th, 2017 by Vincy.

Variable variables are the special features of PHP in PHP. It supports to store the 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/>";


Accessing Array Values

We can use PHP variable variables in arrays. Sometimes we require to separate variable variables with curly braces to avoid confusions. We have examples to see what will happen if don’t 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/>";

Leave a Reply

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

↑ Back to Top

Share this Article