PHP variable name usage method sharing

  • 2020-05-12 02:21:08
  • OfStack

Variables are usually named by the following statement:
 
<?php 
$a = 'hello'; 
?> 

Mutable variable name refers to using the value of a variable as the name of the variable. In the above example, you can set hello to the name of a variable by using two $signs, as shown below.
 
<?php 
$$a = 'world'; 
?> 

Through the two statements above, two variables are defined: the variable $a, which holds "hello", and the variable $hello, which holds "world". Thus, the following language:
 
<?php 
echo "$a ${$a}"; 
?> 

The output of the following statement is exactly 1:
 
<?php 
echo "$a $hello"; 
?> 

They all output: hello world.
In order to use array mutable variable names, you need to resolve 1 ambiguity problem. That is, if you write $$a[1], the parser needs to know whether you mean to use $a[1] as a variable or $$a as a variable. [1] refers to the index of the variable. The syntax for resolving this ambiguity is: ${$a[1]} in case 1 and ${$a}[1] in case 2.
Class properties can also be accessed by variable property names. The variable property name is obtained from the scope of access to the variable where the call was made. For example, if your expression looks like this: $foo- > $bar, then the runtime will look for the variable $bar in the local variable range, and its value will be used as a property name of the $foo object. You can also use $bar if it's an array.
Example 1 variable names
 
<?php 
class foo { 
var $bar = 'I am bar.'; 
} 
$foo = new foo(); 
$bar = 'bar'; 
$baz = array('foo', 'bar', 'baz', 'quux'); 
echo $foo->$bar . "n"; 
echo $foo->$baz[1] . "n"; 
?> 

The above example will output the following results:
I am bar.
I am bar.
warning
Note that mutable variable names cannot be used on super global array variables in PHP functions and classes. The variable $this is also a special variable that cannot be named dynamically.

Related articles: