What are php reference variables? How to define reference variables? This article will briefly introduce the basic concepts and working methods of reference variables in PHP from the memory space, as well as a common example.
What is a reference variable? In PHP, what symbols are used to define reference variables?
Different names access the same variable content, use & to express .
COW(copy on write)
A common method of memory optimization, this method is also used in PHP to optimize memory.
Copy on write, that is, only when one or more variables are written, a copy of the memory will be copied and its contents will be modified.
Use memory_get_usage() in PHP to observe memory changes
Unused & (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());
Running results:
There is not much difference in the memory between the first and second times, but there is a big difference in the third time
Using &
$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());
Running results:
Using reference to pass value memory Parsing analysis:
##$a occupies A memory space in the memory when assigned,
$b=&$ When a
$b points to the same memory space, when
$a changes, the memory space occupied by
$b will follow
$a changes
unset() will only dereference and not destroy the space
$a=1; $b=&$a; unset($b); echo $a;
1
#$a is assigned $b=&$a and then $a and $b go straight to the same memory space , when unset($b) cancels the reference of $b to $a, so that $b no longer points to the memory space of $aDigressionThe object itself is passed by reference
class Person { public $name="zhangsan"; } $p1 =new Person; xdebug_debug_zval('p1'); $p2 =$p1; xdebug_debug_zval('p1'); $p2->name="lisi"; xdebug_debug_zval('p1');
Result analysis:
After the object is instantiated and passed by reference
$p1Case$p2
always points to the same memory space
<?php $data = ['a', 'b', 'c']; foreach($data as $key => $val) { $val = &$data[$key]; } var_dump($data);
When the program is running, what is the value of the variable $data after each loop ends?
After the program execution is completed, what is the value of the variable $data?
Related recommendations:
php variable reference and object reference Detailed introduction_PHP tutorial
phpDetailed introduction to variable reference and object reference
The above is the detailed content of What are php reference variables? Example explanation of php reference variables. For more information, please follow other related articles on the PHP Chinese website!