PHP Variable Variables
A variable variables in PHP is the value of a variable that is defined and treats that as the name of a variable. In the given example, hello, can be used as the name of a variable by using two dollar signs. i.e. we use double $ signs instead of one.
Introduction to the PHP variable variables
It is sometimes useful to be able to have variable variable names. That is, a variable name that may be changed and utilized dynamically. A normal variable is set with a sentence like:
For example, the following defines a variable with the name $text that holds a string value "hello".
<?php
$text = 'hello';
?>
A variable variable takes the value of a variable and treats that as the name of a variable. In the above example, hello, can be used as the name of a variable by using two dollar signs.
In this script, a variable's name can be determined from the value of another variable.
<?php
$$text = 'world';
?>
At this point, two variables have been declared and saved in the PHP symbol tree: $text with the value "hello" and $hello with the value "world" As a result, this statement is written in two ways to produce the same output:
<?php
echo "$text ${$text}";
?>
the same output is generated by the following:
<?php
echo "$text $hello";
?>
By implementing code in two diferent ways, produces the same results: hello world.
Output:
hello world
Complete Code Example:
Filename: php-variable-variables.php
<?php
$text = 'hello';
$$text = 'world';
echo $$text."<br/>"; // output: world
echo "$text ${$text}"."<br/>"; // output: hello world
echo "$text $hello"."<br/>"; // output: hello world
?>
Output:
Output: PHP Variable Variables
How it works
- First, define a variable $text that stores the value in string 'hello'.
- Second, define a variable variable with double dollar sign $$ and using the same variable name as before "text", that stores the string value 'world'. Note that we use double $ signs instead of one. By doing this, we creates another variable with the name $hello.
- Third, display the value of the $text variable.
Conclusion:
PHP variable variables are variables whose names are set dynamically.
Warning
Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.