PHP references some pointers similar to the C language, but some important features are different from the C language pointers. if you do not pay attention to them, it will lead to a program BUG. foreach operates on copying an array or object, but PHP5 can use the reference operation to operate the object element itself.
The code is as follows:
$ A = array (1, 2 );
$ B = array (11, 12 );
Foreach ($ a as & $ r ){
}
Foreach ($ B as $ r ){
}
Echo $ a [1]; // output 12
The intention of the two loops may be: the first loop needs to modify the element content in the loop, so reference is used; but the second loop only treats $ r as a temporary variable. but why does the value of $ a [1] change?
After the iteration of $ a is complete, $ r is a reference of $ a [1]. changing the value of $ r is to change $ a [1]. in this case, you may wonder that $ r is not modified in the code or $ a [1?
In fact, foreach operates on copying arrays. Therefore, the next iteration is equivalent:
The code is as follows:
For ($ I = 0; $ I $ R = $ B [$ I]; // modified $ r! Equivalent to $ a [1] = $ B [$ I];
}
To avoid this situation, you should execute
The code is as follows:
Unset ($ r );
Delete the variable $ r from the current environment (reference variable ).
Even if it is not the previous example, after the first iteration, it is very likely that similar statements will be executed again:
The code is as follows:
$ R = 123;
Loop variables are usually temporary variables. the same variable name represents different things in different places of the code, but the scope of the variables exists outside the loop. this is the disadvantage of this scope rule. In addition, the "variable is used without declaration" is added, and the variable has no type.
Therefore, to use reference variables in PHP, you should unset () after the reference is used. all variables should be unset () before use ().