Home >>PHP Tutorial >PHP $ and $$ Variables
PHP $$var uses the value of the variable whose name is the value of $var. It means $$var is known as reference variable where as $var is normal variable. It allows you to have a "variable's variable" - the program can create the variable name the same way it can create any other string.
<?php $name="Rajeev"; $name="Sanjeev"; echo $name."<br/>"; echo $name."<br/>"; echo $Rajeev; ?>
In the above example $name is just a variable with string value="Rajeev". $$name is reference variable .
$$name uses the value of the variable whose name is the value of $name.
echo $name print the value: Rajeev echo $$name print the value:Sanjeev \ value of this($name) variable is act as reference of second variable($$name).
echo $rajeev print the value :Sanjeev \ Here $Rajeev is also act as reference variable.
Example - 2
<?php $x = "100"; $x = 200; echo $x."<br/>"; echo $x."<br/>"; echo "$100"; ?>
You first assign the value of a variable, ($x) as the name of another variable.
When you set $x to a value, it will replace that variable name with the value of the variable you provide.
variable $x hold value = 100.
$$x(reference variable) hold value = 200. now we want to print the value.
echo $x gives output:100
echo $$x gives output:200.
echo $100 gives value.200. because it also act as a reference variable for value = 200.
Example 3.
<?php $name="Rajeev"; ${$name}="Sanjeev"; echo $name."<br/>"; echo ${$name}."<br/>"; echo "$Rajeev"."<br/>"; ?>
Example 4.
<?php $name="Ravi"; ${$name}="Ranjan"; ${${$name}}="Rexx"; echo $name; echo ${$name}; echo ${${$name}}; ?>
variable $name hold value ="ravi"
variable ${ $name } hold value ="Ranjan" // it also declare like ${Ravi}.
variable ${$ {$name} } hold value ="Rexx" // it act as "variable's of variable of variable" reference.
echo $name show output:ravi
echo ${ $name } show output:Ranjan.
echo ${ $ {$name} } show output :Rexx