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);
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 死了!
<?php $a = 1; $b = &$a; unset($a); var_dump($a); var_dump($b);
Notice: Undefined variable: a in E:\amp\apache\htdocs\index.php on line 5 NULL int(1)
$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);
NULL NULL
$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!