Home  >  Article  >  Backend Development  >  PHP's destructor and garbage collection mechanism_PHP tutorial

PHP's destructor and garbage collection mechanism_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:33:24836browse

Destructor: Executed when an object becomes garbage or when the object is explicitly destroyed.

GC(Garbage Collector)

In PHP, when no variable points to this object, the object becomes garbage. PHP will destroy it in memory.

This is PHP's GC (Garbage Collector) garbage disposal mechanism to prevent memory overflow.

When a PHP thread ends, all memory space currently occupied will be destroyed, and all objects in the current program will also be destroyed.

__destruct() destructor

__destruct() destructor is executed when the garbage object is recycled.

The destructor can also be called explicitly, but don't do it.

The destructor is automatically called by the system. Do not call fictitious functions of an object in the program.

Destructor cannot take parameters.

As shown in the program below, all objects are destroyed before the program ends. The destructor is called.

<?
class Person {
	public function __destruct(){
		echo '析构函数现在执行了 <br />';
		echo '这里一般用来设置、关闭数据库、关闭文件等收尾工作';
	}
}
$p = new Person();
for($i = 0; $i < 5; $i++){
	echo "$i <br />";
}
?>

Program execution result:

0 
1 
2 
3 
4 
析构函数现在执行了 
这里一般用来设置、关闭数据库、关闭文件等收尾工作

When the object is not pointed to, the object is destroyed.

<?
class Person {
	public function __destruct(){
		echo '析构函数现在执行了 <br />';
	}
}
$p = new Person();
$p = null; // 析构函数在这里执行了
$p = "abc"; // 一样的效果
for($i = 0; $i < 5; $i++){
	echo "$i <br />";
}
?>

Program execution result:

析构函数现在执行了 
0 
1 
2 
3 
4 

In line 10 of the above example, we set $p to empty or assign $p a string in line 11, so that the object pointed to by $p becomes a garbage object. PHP trashes this object.

php unset variable

<?
class Person {
	public function __destruct(){
		echo '析构函数现在执行了 <br />';
	}
}
$p = new Person();
$p1 = $p;
unset($p);
echo '现在把 $p 被销毁了,对象是否也被销毁了呢?<br />';
for($i = 0; $i < 5; $i++){
	echo "$i <br />";
}
echo '现在再把 $p1 也销毁掉,即已经没有指向对象的变量了<br />';
unset($p1); // 现在没有指向对象的变量了,析构函数在这里执行了
?>

Program execution result:

现在把 $p 被销毁了,对象是否也被销毁了呢?
0 
1 
2 
3 
4 
现在再把 $p1 也销毁掉,即已经没有指向对象的变量了
析构函数现在执行了 

unset destroys the variable pointing to the object, not the object.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/752488.htmlTechArticleDestructor: Executed when an object becomes garbage or when the object is explicitly destroyed. GC (Garbage Collector) In PHP, when no variable points to this object, this object becomes...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn