Explanation of PHP destructor destruct and garbage collection mechanism

  • 2021-12-04 18:23:10
  • OfStack

Destructor

Executes when an object becomes garbage or when the object is explicitly destroyed.

The destructor provided in PHP5 is __destruct, which corresponds to the construction method __construct.

Garbage Collection-GC (Garbage Collector)

In PHP, when no variables point to the object, the object becomes junk and PHP destroys it in memory.

This is the GC (Garbage Collector) garbage disposal mechanism of PHP, and garbage charging can prevent memory overflow.

When an PHP thread ends, all currently occupied memory space is destroyed, and all objects in the current program are also destroyed.

__destruct() Destructor, which is executed when garbage objects are collected.

Destructors are called automatically by the system and can be called explicitly, but don't do this.

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


<?php
class Person {
 public function __destruct(){
 echo ' The destructor is now executed  <br />';
 echo ' Here 1 It is used to set up, close the database, close the file and other finishing work ';
 }
}
$p = new Person();
for($i = 0; $i < 5; $i++){
 echo "$i <br />";
}
?>

Program running results:
0
1
2
3
4
The destructor is now executed
Here 1 is used to set up, close the database, close the file and other finishing work

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


<?php
class Person {
 public function __destruct(){
 echo ' The destructor is now executed  <br />';
 }
}
$p = new Person();
$p = null; //  The destructor is executed here 
$p = "abc"; // 1 Sample effect 
for($i = 0; $i < 5; $i++){
 echo "$i <br />";
}
?>

Program running results:

The destructor is now executed
0
1
2
3
4

In the above example, we set $p to null or assign $p1 a string, so that the object that $p previously pointed to becomes a junk object. PHP garbage destroys this object.

php unset variable


<?php
class Person {
 public function __destruct(){
 echo ' The destructor is now executed  <br />';
 }
}
$p = new Person();
$p1 = $p;
unset($p);
echo ' Now put  $p  Has been destroyed, has the object also been destroyed?  <br />';
for($i = 0; $i < 5; $i++){
 echo "$i <br />";
}
echo ' Now put it again  $p1  Destroy it, too , That is, there are no variables pointing to the object <br />';
unset($p1); //  There are no variables pointing to objects now , The destructor is executed here 
?>

Program running results:

Now that $p has been destroyed, has the object also been destroyed?
0
1
2
3
4
Now destroy $p1, that is, there are no variables pointing to the object
The destructor is now executed

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

Summarize


Related articles: