Destructors and php's garbage collection mechanism explained in detail

  • 2020-10-23 20:54:43
  • OfStack

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

GC(Garbage Collector)

In PHP, an object becomes garbage when there are no variables pointing to it. PHP will destroy it in memory.

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

When an PHP thread terminates, all the memory space currently occupied is destroyed, as are all objects in the current program.

Succdestruct () destructor

The destructor with SUCCdestruct () is executed when the garbage object is recycled.

Destructors can also be explicitly called, but do not do so.

Destructors are automatically called by the system. Do not call a dummy function of an object in the program.

Destructors cannot take arguments.

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


<? 
class Person { 
    public function __destruct(){ 
        echo ' The destructor is now executed  <br />'; 
        echo ' Here, 1 Typically used to set up, close databases, close files, and so on '; 
    } 
} 

$p = new Person(); 
for($i = 0; $i < 5; $i++){ 
    echo "$i <br />"; 
} 

?> 

Program operation Results:
0
1
2
3
4

The destructor is now executed
This is generally used to set up, close databases, close files, and so on

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


<? 
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 The effect of the sample  
for($i = 0; $i < 5; $i++){ 
    echo "$i <br />"; 
} 

?> 

Program operation Results:

The destructor is now executed
0
1
2
3
4

In the example above, on line 10, we set $p to null or give $p1 a string on line 11, so that the object that $p previously pointed to becomes a garbage object. PHP destroys the object garbage.
php unset variable


<? 

class Person { 
    public function __destruct(){ 
        echo ' The destructor is now executed  <br />'; 
    } 
} 

$p = new Person(); 
$p1 = $p; 

unset($p); 
echo ' Now the  $p  Is the object destroyed when it is destroyed? <br />'; 

for($i = 0; $i < 5; $i++){ 
    echo "$i <br />"; 
} 

echo ' Now put  $p1  Also destroyed , There are no more variables to point to <br />'; 
unset($p1); //  There are no variables to point to now , The destructor is executed here  

?>   

Program operation 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 more variables pointing to the object

The destructor is now executed

unset destroys the variable that points to the object, not the object.


Related articles: