Home >Backend Development >PHP Tutorial >Detailed analysis of destructor and garbage collection in php

Detailed analysis of destructor and garbage collection in php

黄舟
黄舟Original
2017-07-02 10:11:401205browse

Destructor: Executed when a 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 is executed when the garbage object is recycled.

The destructor can also be called explicitly, but do not do so.

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

The destructor cannot have parameters.

All objects are destroyed before the program ends. The destructor was called.

     <?php    
    class Person{    
       public function destruct() {    
          echo "<br />析构函数在这里执行";    
          echo "<br />这里一般用来放置,关闭数据库,关闭文件等等收尾工作。";    
       }    
    }    
    $p = new Person();    
    for ($i = 0; $i < 5; $i++) {    
       echo "<br /> $i";    
    }  
    //我们在这里看到,在PHP程序结束前,对象被销毁了。    
    ?>

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

    <?php    
    class Person {    
       public function destruct() {    
          echo "<br />析构函数在这里执行";    
          echo "<br />这里一般用来放置,关闭数据库,关闭文件等等收尾工作。";    
       }    
    }    
    $p = new Person();    
    $p = null;    
    //我们在这里看到,析构函数在这里被执行了。    
    for ($i = 0; $i < 5; $i++) {    
       echo "<br /> $i";    
    }    
    ?>

We set $p to empty or give $p a string on line 11, so that the object pointed to by $p before becomes a garbage object. PHP garbage destroys this object.

unset variable

    <?php    
    class Person {    
       public function destruct() {    
          echo "<br />析构函数在这里执行<br />";    
       }    
    }    
    $p = new Person();    
    $p1 = $p; //设定新引用变量$p1也指向这个对象    
    unset($p);    
    echo "是否看到/$p被销毁,对象也被销毁呢?";    
    for ($i = 0; $i < 5; $i++) {  
       echo "<br /> $i";    
    }    
    unset($p1);    
    echo "我们看到这里,析构函数被执行了";    
    ?>


When unset a reference variable, unset destroys the variable pointing to the object, not the object.

The above is the detailed content of Detailed analysis of destructor and garbage collection in php. For more information, please follow other related articles on the PHP Chinese website!

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