Application of variable variables in PHP_PHP tutorial

WBOY
Release: 2016-07-13 10:31:41
Original
747 people have browsed it

Sometimes variable variable names bring great convenience to programming. That is to say, variable names can be named and used dynamically. Usually variables are named with statements like the following:

  1. $a = 'hello';
  2. ?>

Variable variable name refers to using the value of a variable as the name of the variable. In the example above, you can set hello to the name of a variable by using two $ signs, like below.

  1. $$a = 'world';
  2. ?>

Through the above two statements, two variables are defined: variable $a, which contains "hello" and variable $hello, which contains "world". So, the following language:

  1. echo "$a ${$a}";
  2. ?>

The output is exactly the same as the following statement:

  1. echo "$a $hello";
  2. ?>

They all output: hello world. In order to use an array's mutable variable name, you need to resolve an ambiguity problem. That is, if you write $$a[1], the parser needs to understand whether you mean to treat $a[1] as a variable, or to treat $$a as a variable. [1] refers to this variable. index.

The syntax to resolve this ambiguity is:

Use ${$a[1]} in the first case, and ${$a}[1] in the second case.

Class properties can also be accessed via mutable property names. Mutable property names are taken from the access scope of the variable in which the call is made. For example, if your expression is like this: $foo->$bar, then the runtime will look for the variable $bar in the local variable scope, and its value will be used as a property name of the $foo object. It can also be used if $bar is an array.

Example 1 Variable variable name $bar . "n";echo $foo->$baz[1] . "n";?>The above example will output the following result: I am bar.I am bar.

Warning Please note that mutable variable names cannot be used for super global array variables in PHP functions and classes. The variable $this is also a special variable that cannot be dynamically named.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/762035.htmlTechArticleSometimes variable variable names bring great convenience to programming. That is to say, variable names can be named and used dynamically. Usually variables are named through the following statement: ?php $a...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template