Sometimes it is 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 by a declaration, for example:
<?php $a = ' hello ';? >
A mutable variable gets the value of an ordinary variable as the variable name of the variable variable. In the example above, hello uses two dollar sign ($) and can be used as a variable variable. For example:
<?php $a = ' world ';? >
At this point, two variables are defined: $a content is "hello" and $hello content is "world". Therefore, the following statement:
<?php echo "$a ${$a}";? >
Output the exact same result as the following statement:
<?php echo "$a $hello";? >
They all output: Hello world.
To use mutable variables with arrays, you must address an ambiguous question. This is when you write the $ $a [1], the parser needs to know if you want to $a [1] as a variable, or you want $ $a as a variable and take out the value of the variable indexed to [1]. The syntax for solving this problem is to use ${$a [1] for the first case, and ${$a}[1 for the second case).
The properties of a class can also be accessed through a variable property name. The Mutable property name is resolved within the scope of the call. For example, for $bar expression $foo, the $bar is resolved at the local scope and its value is used for the $foo property name. The same is true for $bar, which is an array unit.
You can also use curly braces to clear the bounds of a property name. Most useful is if the property is in an array, or if the property name contains more than one part or if the property name contains an illegal character (for example, from Json_decode () or SimpleXML).
Example #1 Variable Attribute example
<?phpclass Foo { var $bar = ' I am bar '; var $arr = Array (' I am A. ', ' I am B. ', ' I am C. '); var $r = ' I am R. ';} $foo = new Foo (), $bar = ' bar '; $baz = Array (' foo ', ' Bar ', ' baz ', ' Quux '); Echo $foo $bar. "\ n"; $baz echo $foo, [1]. "\ n"; $start = ' B '; $end = ' ar '; echo $foo->{$start. $end}. "\ n"; $arr = ' arr '; echo $foo $arr [1]. "\ n"; Echo $foo->{$arr}[1]. "\ n";? >
The above routines will output:
I am Bar. I am Bar. I am Bar. I am r.i am B.
Warning
Note that in PHP's methods of functions and classes, a hyper-global variable cannot be used as a mutable variable. $this variable is also a special variable that cannot be referenced dynamically.