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 the content is "Hello" and $hello the 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 the $$a[1] parser needs to know if it wants to be $a[1] a variable, or if it wants to be a variable and take $$a out the variable indexed as [1].
Value. The syntax for solving this problem is, in the first case ${$a[1]} , in the second case ${$a}[1] .
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 an $foo->$bar expression, the property name will be resolved at the local scope $bar and its value will be used $foo . Right
Is the same as the $bar 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
<?PHPclassFoo {var $bar= ' I am bar. '; var $arr=Array(' I am A. ', ' I am B. ', ' I am C. ')); var $r= ' I am r. ';}$foo=Newfoo ();$bar= ' Bar ';$baz=Array(' foo ', ' Bar ', ' baz ', ' Quux '));Echo $foo-$bar. "\ n";Echo $foo-$baz[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.
PHP--mutable variables