PHP variable Variables

PHPServer Side ProgrammingProgramming

Introduction

In PHP, it is possible to set variable name dynamically. Such a variable uses value of an existing variable as name. A variable variable is defined with two $ signs as prefix

Example

 Live Demo

<?php
$var1="xyz"; //normal variable
$$var1="abcd";//variable variable
echo $var1 . "\n";
echo $$var1 . "\n";
echo "{$$var1} $xyz";
?>

Output

This script produces following output

xyz
abcd
abcd abcd

Note that value of $$var1 is same as $xyz, xyz being value of $var1.

Numeric value of normal variable cannot be used as variable variable

Example

 Live Demo

<?php
$var1=100; //normal variable
$$var1=200;//variable variable
echo $var1 . "\n";
echo $$var1 . "\n";
echo $100;
?>

Output

When this script is executed, following result is displayed

PHP Parse error: syntax error, unexpected '100' (T_LNUMBER), expecting variable (T_VARIABLE) or '{' or '$' line 6

It is also possible to define a variable variable in terms of an array subscript. In following example, a variable variable is defines using 0th element of a normal array

Example

 Live Demo

<?php
$var1=array("aa","bb"); //normal variable
${$var1[0]}=10;//variable variable with array element
echo $var1[0] . "\n";
echo $aa . "\n";
echo ${$var1[0]} . "\n";
?>

Output

This will produce following result −

aa
10
10

Class properties are also accessible using variable property names. This feature is useful when a propery name is made up of an array.

Example

<?php
var $u = "Architecture";
var $ugCourses = array("CSE","MECH","CIVIL");
$obj = new branches();
$courses = "ugCourses";
echo $obj->{$courses[0]} . "\n";
echo $obj->{$courses}[0] . "\n";
?>

Output

This will produce following result −

Architecture
CSE
raja
Published on 19-Sep-2020 18:40:40
Advertisements