Variable variables in php
Sometimes it is convenient to use variable variable names. That is to say, The variable name of a variable can be dynamically set and used. An ordinary variable is set through declaration, for example:
<?php $a = 'hello'; ?>
A variable variable obtains the value of an ordinary variable as the variable name of the variable variable. In the above example hello uses two dollar signs ($), it can be used as a variable variable.
Example 1:
<?php $$a = 'world'; ?>
At this time, both variables are defined: the content of $a is "hello" and the content of $hello is "world".
Example 2:
<?php echo "$a ${$a}"; ?>
The following statement outputs exactly the same result:
<?php echo "$a $hello"; ?>
They will all 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 takes out the variable The value with index [1].
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 variable property names. Mutable property names will be resolved within the scope of the call. For example, for the expression $foo->$bar, $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 unit.
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:<?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 . "
";
echo $foo->$baz[1] . "
";
$start = 'b';
$end = 'ar';
echo $foo->{$start . $end} . "
";
$arr = 'arr';
echo $foo->$arr[1] . "
";
echo $foo->{$arr}[1] . "
";
?>
: This article is reproduced from: https://www.cnblogs.com/ryanzheng/p/9133381.htmlRecommended tutorial: " The above is the detailed content of Variable variables in php (detailed code explanation). For more information, please follow other related articles on the PHP Chinese website!I am bar.
I am bar.
I am bar.
I am r.
I am B.