Home >Backend Development >PHP Tutorial >php variable variables

php variable variables

伊谢尔伦
伊谢尔伦Original
2016-11-24 13:45:091194browse

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 = &#39;hello&#39;;
?>

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 = &#39;world&#39;;
?>

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 = &#39;I am bar.&#39;;
    var $arr = array(&#39;I am A.&#39;, &#39;I am B.&#39;, &#39;I am C.&#39;);
    var $r = &#39;I am r.&#39;;
}
$foo = new foo();
$bar = &#39;bar&#39;;
$baz = array(&#39;foo&#39;, &#39;bar&#39;, &#39;baz&#39;, &#39;quux&#39;);
echo $foo->$bar . "\n";
echo $foo->$baz[1] . "\n";
$start = &#39;b&#39;;
$end = &#39;ar&#39;;
echo $foo->{$start . $end} . "\n";
$arr = &#39;arr&#39;;
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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn