Home > Article > Backend Development > What are the 2 ways to destroy variables in php
Two methods for PHP to destroy variables: 1. Use the unset() function, the syntax "unset($varname)"; 2. Assign the value to the specified variable as "NULL", the syntax "$varname=null;" .
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
PHP variables or The destruction of objects can be divided into explicit destruction and implicit destruction:
1. Explicit destruction. When the object is not referenced, it will be destroyed, so we can unset or assign NULL to it;
2. Implicit destruction. PHP is a scripting language. When the last line of code is executed, all applied memory must be released.
Therefore, there are two ways to destroy variables. :
unset()
##$varname=null
For example:
class Human { public $name = '张三'; public $gender = null; public function __destruct() { echo '死了!<br />'; } } $a = new Human(); $b = $c = $d = $a; unset($a); $d=null; echo '<hr />'; var_dump($a); echo '<hr />'; var_dump($b); echo '<hr />'; var_dump($c); echo '<hr />'; var_dump($d);The result is as follows:
Notice: Undefined variable: a in /Library/WebServer/Documents/test.php on line 42 NULL object(Human)#1 (2) { ["name"]=> string(6) "张三" ["gender"]=> NULL } object(Human)#1 (2) { ["name"]=> string(6) "张三" ["gender"]=> NULL } NULL 死了!First we need to know that in PHP, variable names are stored in the memory stack , it points to the address of specific memory in the heap, and finds the memory in the heap through the variable name; therefore we can draw the conclusion:
<?php $a = 1; $b = &$a; unset($a); var_dump($a); var_dump($b);The result is:
Notice: Undefined variable: a in E:\amp\apache\htdocs\index.php on line 5 NULL int(1)So unset( ) does not actually destroy the memory value in the variable, it just cuts off the relationship between the variable and the memory, and removes the variable name, but the memory will not be released as long as it is still referenced; in PHP, the object Pass-by-value defaults to pass-by-reference, which also explains that in the Human class, $a is unset(), but $b =$c = $d still has value.
$varname=null, the variable name still exists, but the memory value has been deleted. So what about in the case of pass-by-reference? Example:
<?php $a = 1; $b = &$a; $a=null; var_dump($a); var_dump($b);The output result is:
NULL NULLSo,
$varname=null, although the variable name and memory pointer still exist, the value in the memory is Completely deleted.
PHP Video Tutorial"
The above is the detailed content of What are the 2 ways to destroy variables in php. For more information, please follow other related articles on the PHP Chinese website!