This article mainly introduces the PHP reference variable knowledge detailed, has a certain reference value, now share to everyone, the need for friends can refer to
Concept: Referencing in PHP means accessing the same variable content with a different name;
Definition: PHP uses ' & ' to define reference variables;
When a reference is not used, the variable takes a write-time copy mechanism (COW): A copy of the memory is copied on the write to modify, for example
Define a variable $ A = range (0,1000); Var_dump (Memory_get_usage ()); Print memory usage//define a variable b$b = $a; At this point, $b and $ A point to the same memory space Var_dump (Memory_get_usage ()), and//When a or B is written, a block of memory is copied to modify $ A = range (0,1000); Var_dump (memory_get_ Usage ());
Run Result: Memory usage is not much different during first and second printing, and the third time has changed significantly, which indicates that memory has replicated when a writes.
Define a variable $ A = range (0,1000); Var_dump (Memory_get_usage ()); Print memory usage//define a variable b$b = & $a; Assigning a space to B,a and B to the same space Var_dump (Memory_get_usage ());//When a or B write occurs, the memory does not replicate $ A = range (0,1000); Var_dump (memory_get_ Usage ());
Run Result: Memory has never changed significantly
Validation through the Zval variable container
Print $ A = range (0,3) through the Zval variable container, xdebug_debug_zval (' a '),//print the number of variables that point to memory space, and whether it is referenced $c =& $a; Xdebug_debug_zval (' a '); $c = Range (0,3); Xdebug_debug_zval (' a ');
Operation Result:
When writing to C, there are still 2 variables pointing to memory, no write-time replication occurs
Unset only cancels the reference and does not destroy the space
In PHP, the object itself is a reference value, without the use of reference symbols
Class person{public $name = "Zhangsan";} $p 1 = new person (), Xdebug_debug_zval (' P1 '), $p 2 = $p 1;xdebug_debug_zval (' P1 '); $p 2->name = "Lesi"; Xdebug_debug_zval ( ' P1 ');