Detailed explanation of the use of variable variable '$$' in php

伊谢尔伦
Release: 2023-03-10 22:30:01
Original
2151 people have browsed it

Variable variables

Sometimes it is very convenient to use variablevariable names. That is, the variable name of a variable can be set and used dynamically. An ordinary variable is set through declaration, for example:

Copy after login

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:

Copy after login

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:

Copy after login

The following writing methods are more accurate and will output the same result:

Copy after login

They will both output: hello world.

To use mutable variables witharrays, 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 theindex## 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.


        
Copy after login

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 inNote.)#$$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}";
Copy after login

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:

Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn