What are Variable Variables in PHP?

In this article, we will learn how PHP dynamically declares a variable. That is reference variable also known as Variable Variables in PHP.

PHP allows the programmer to create and use the reference of an existing variable by making another variable out of that normal variable.

What is Variable in PHP

Variable stores data like integer, float, string and etc. In PHP, a variable is declared with the dollar($) symbol.




Syntax:-

$name_of_the_variable=Value;

Example:-

<?php
$variable=5; //creating an integer variable
echo "value of variable:".$variable;
?>

Output:-

value of variable:5

Note:-

In PHP, the datatype of a variable is dynamic in nature i.e. datatype of the variable depends on what type of data is present in that variable.

Reference variable(variables) or Variable Variables in PHP

It is the reference to a normal variable i.e. it stores the value of a normal variable as the variable name. It is declared with the double dollar($$) symbol.

Syntax:-

$$name_of_the_variable=value;

Example:-

<?php

//declaring a variable
$name_of_country="India";

echo "Value in \$name_of_country:".$name_of_country."</br>";

//creating reference to another variable
$$name_of_country="WestBengal";
echo "Value of the reference to \$name_of_country:". $$name_of_country."</br>";
echo "Value of \$India:".$India;//Same as $$name_of_country
?>

Output:-

Value in $name_of_country:India
Value of the reference to $name_of_country:WestBengal
Value of $India:WestBengal

Let us take another example to clarify the reference variable concept,

<?php  

//declaring a normal variable
$name="India";  
echo $name. "<br>"; 

//creating reference to normal variable
${$name}="Wb";
echo ${$name}. "<br>";  
echo $India. "<br>";  //Same as $$name

//creating reference to reference variable  
${${$name}}="Kolkata";  
echo ${${$name}}. "<br>";  
echo $Wb. "<br>";  //Same as $$$name and $$India
?>

Output:-

India
Wb
Wb
Kolkata
Kolkata

From the above article, we can conclude that there is no limit for creating and accessing references from a normal variable.

If you have any doubts on the above article, leave a comment below.

See also,


Leave a Reply

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