Sometimes it is convenient to use mutable variable names. That is to say, the variable name of a variable can be set and used dynamically. An ordinary variable is set by declaration, for example:
<?php $a = 'hello'; ?>
A variable variable gets 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, the following statement:
<?php echo "$a ${$a}"; ?>
outputs exactly the same result as the following statement:
<?php echo "$a $hello"; ?>
They 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 extracts the variable with index [1] value. The syntax to solve this problem is to use ${$a[1]} for the first case and ${$a}[1] for the second case.
Class properties can also be accessed through mutable property names. Mutable property names will be resolved within the scope of the call. For example, for the $foo->$bar expression, $bar will be parsed in the local scope and its value will be used as the property name of $foo. The same is true for $bar when it is an array cell.
You can also use curly braces to clearly delimit attribute names. Most useful when the property is in an array, or the property name contains multiple parts or the property name contains illegal characters (such as from json_decode() or SimpleXML).
Example #1 Variable attribute example
<?php class 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"; 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 routine will output:
I am bar. I am bar. I am bar. I am r. I am B.
Warning
Note that in PHP functions and class methods, superglobal variables cannot be used as variable variables. The $this variable is also a special variable and cannot be referenced dynamically.