Home > Article > Backend Development > Detailed explanation of the use of variable variable "$$" in php
Sometimes it is very convenient to use variable variable names. That is, the variable name of a variable can be set and used dynamically. An ordinary variable is set through declaration, for example:
<?php $a = "hello"; ?>
A variable variable obtains the value of an ordinary variable as the variable name of the variable variable. In the above example, hello can be used as a variable variable after using two dollar signs ($). For example:
<?php $$a = "world"; ?>
At this time, two variables are defined: the content of $a is "hello" and the content of $hello is "world". Therefore, it can be expressed as:
<?php echo "$a ${$a}"; ?>
The following writing methods are more accurate and will output the same result:
<?php echo "$a $hello"; ?>
They will both output: hello world.
To use mutable variables with arrays, an ambiguity must be resolved. This is when writing $$a[1], the parser needs to know whether it wants $a[1] as a variable, or whether it wants $$a as a variable and takes out the index## of that variable. # is the value of [1]. The syntax to solve this problem is to use ${$a[1]} for the first case and ${$a}[1] for the second case.
<?php $a = 'hello'; $$a = 'world'; echo "$a ${$a}";In the second sentence of the above code, we use a variable with two dollar signs, so this variable here is our variable variable. Let’s explain in detail starting from the first sentence: Our first sentence defines a variable a, and its value is hello.
The second sentence we are: (Because we found that the dollar sign has a special meaning, I The explanation is written in Note.)#$$a = 'world'; //Here our $$a is a variable variable; here $$a represents $(the value of $a), so what does this mean? Is the value of our $a here hello? Then $$a means replacing $a with its value, then it is $hello. So it means $hello='world'; I don't know if you understand? //Is our $a the value of hello? Then $$a, is the $a in it hello? If $a is replaced with hello, then it is $hello. Then it means that the value of $hello is equal to world. This understands Come on.
echo "$a ${$a}";
It is necessary to add curly brackets: {} If not, the variable name will be output. You will understand after trying it, but it will be incorrect. In fact, the above code is the same as the following code:
<?php $a = 'hello'; $$a = 'world'; echo "$a $hello"; ?>
The above is the detailed content of Detailed explanation of the use of variable variable "$$" in php. For more information, please follow other related articles on the PHP Chinese website!