Home > Article > Backend Development > Issues that need to be paid attention to when using PHP's variable variable names in arrays and classes_PHP Tutorial
Sometimes variable variable names bring great convenience to programming. That is to say, variable names can be named and used dynamically. Usually variables are named through the following statements:
$a = 'hello';
Variable variable names refer to using the value of a variable as the name of the variable. In the example above, you can set hello to the name of a variable by using two $ signs, like below.
$$a = 'world';
Through the above two statements, two variables are defined: variable $a, which contains "hello" and variable $hello, The installed content is "world". Therefore, the following language:
echo "$a ${$a}";
is exactly the same as the output of the following statement:
echo "$a $hello ";
They all output: hello world.
But in order to use mutable variable names for arrays, you need to resolve an ambiguity problem. That is, if you write $$a[1], the parser needs to understand whether you mean to treat $a[1] as a variable, or to treat $$a as a variable. [1] refers to this variable. index. The syntax to resolve this ambiguity is: use ${$a[1]} in the first case and ${$a}[1] in the second case.
Class properties can also be accessed via mutable property names. Mutable property names are taken from the access scope of the variable in which the call was made. For example, if your expression is like this: $foo->$bar, then the runtime will look for the variable $bar in the local variable scope, and its value will be used as a property name of the $foo object. It can also be used if $bar is an array.