PHP Variable Varibles

by Vincy. Last modified on July 3rd, 2022.

Variable variables are the special features of PHP in PHP. It supports storing 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,

<?php
$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.

<?php

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 confusion. We have examples to see what will happen if don’t use curly braces in PHP variable variables.

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

${$entertainment[0]} will return $m which is not found and cause an 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,

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

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

<?php

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/>";
?>
Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page