There are several concepts that need to be clarified first:
The values of variable names and variables are two concepts,
Variable name refers to a memory space,
The value of the variable is stored in the space.
The difference between the value of a pass and the reference
Pass by value
1. Within the scope of the function, any changes that are worthwhile are ignored outside the function.
2. When passing by value, PHP must copy the value, if it is a large string or object, this is a costly operation, consuming memory.
Pass by reference
1. Within the function is worth any change, can be reflected outside the function
2. No need to copy values when passing by reference, good for performance improvement
Example one:
1 <? PHP 2 $a= ' Hello World '; 3 $b = &$a; 4 unset ($a); // It just unlocks the corresponding relationship between the variable name and value. $ A is destroyed, but $b still exists 5 Echo $b; // Hello World, memory is recycled only if there are no variable references to address.
unset ($a) ago
After unset ($b)
Example two:
1<?PHP2 3 $data=Array(' A ', ' B ', ' C ');4 foreach($data as $key=$value){5 $value=&$data[$key];/** Reference assignment, will $value point to $data[$key] address,6 * Next Change the value of $value, also changed the $data[$key]7 * value, which is the key to understanding this problem. 8 */ 9 Print_r($data);//The $data is printed out after each cycle for easy analysis of the results. Ten Echo' <br/> '; One } A - Print_r($data); - the Array([0] = a [1] = b [2] = = c)//The first loop, the array does not change, but $value points to $data[1] - Array([0] = b [1] = b [2] = = c)//The second loop, at which time B is assigned to the $value, so $data[1] in the second cycle has changed, while $value Point to $data[2]; - Array([0] = b [1] = c [2] = = c)//third cycle, the process is the same as the second time, the value of $data[2] has changed
PHP Reference Pass Value