$$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. .
Eg i
<?php
$name="Rajeev";
$$name="Sanjeev";
echo $name."<br/>";
echo $$name."<br/>";
echo $Rajeev;
?>
Output
Rajeev
Sanjeev
Sanjeev
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.
Eg ii
<?php
$x = "100";
$$x = 200;
echo $x."<br/>";
echo $$x."<br/>";
echo "$100";
?>
Output
100
200
200
In the above example
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.
Eg iii
<?php
$name="Rajeev";
${$name}="Sanjeev";
echo $name."<br/>";
echo ${$name}."<br/>";
echo "$Rajeev"."<br/>";
?>
|
Output
Rajeev
Sanjeev
Sanjeev
Eg iv
<?php
$name="Ravi";
${$name}="Ranjan";
${${$name}}="Rexx";
echo $name;
echo ${$name};
echo ${${$name}};
?> |
Output
Ravi
Ranjan
Rexx
In the above example
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