What is a PHP reference variable? How do I define a reference variable? This article will briefly summarize the basic concepts, working methods, and a common example of reference variables in PHP from memory space.
Concept
What are reference variables, and what symbols are used to define reference variables in PHP?
Different names access the same variable content, using the & representation.
COW (copy on Write)
A common means of memory optimization, which is also used in PHP to optimize memory.
Copy-on-write, that is, when one or more of the variables are written, a copy of the memory is copied and the contents are modified.
Use Memory_get_usage () to observe memory changes in PHP
Demonstrate
& not Used (reference variable)
$a = range (0,1000); Var_dump (Memory_get_usage ()); $b = $a; ' var_dump (Memory_get_usage ()); $a = range (0,1000); Var_dump (Memory_get_usage ());
Operation Result:
Memory in the first and second time is not too big difference, the third time produces a big difference
Use &
$a = range (0,1000); Var_dump (Memory_get_usage ()); $b = & $a; Var_dump (Memory_get_usage ()); $a = range (0,1000); Var_dump (Memory_get_usage ());
Operation Result:
When using reference-valued memory parsing analysis:
$a
When assigned to occupy a memory space in memory, pointing to $b=&$a
the $b
same memory space, the $a
memory space occupied when the change occurs $b
will follow the $a
change
unset
unset()
Only dereference will not destroy space
$a =1; $b =& $a; unset ($b); Echo $a;
Output Result:1
Memory Space Analysis:
$a is assigned a value $b =& $a after $ A and $b go straight into the same memory space, when unset ($b) cancels the $b to $ A reference, so that $b does not point to $ A in the memory space
Off Topic
The object itself is a reference pass
Class person{public $name = "Zhangsan";} $p 1 =new person;xdebug_debug_zval (' P1 '), $p 2 = $p 1;xdebug_debug_zval (' P1 '); $p 2->name= "Lisi"; Xdebug_debug_zval (' P1 ');
Operation Result:
Results Analysis:
After the object is passed by reference after it
$p1
is
$p2
instantiated Always point to the same memory space
Case
<?php $data = [' A ', ' B ', ' C ']; foreach ($data as $key = + $val) { $val = & $data [$key]; } Var_dump ($data);
Write the output of the program as above?
What is the value of the variable $data at the end of each cycle when the program runs?
What is the value of the variable $data after the execution of the program?
Memory Changes and parsing: