when to use destructor in php?

后端 未结 4 384
别跟我提以往
别跟我提以往 2020-12-29 02:42

what is the main purpose of a destructor?

could you give any examples of what i might want to run when a object is deleted?

相关标签:
4条回答
  • 2020-12-29 03:11

    Say I have a Result class that is a wrapper (implementing Iterator, among other niceties) for the mysqli_result object. When I destroy one of my Result objects, I want to be sure to call the free() method on the mysqli_result object to reclaim the memory it was using. So I do that in the destructor of my Result class.

    0 讨论(0)
  • 2020-12-29 03:18

    Reference for book

    Destructor often use for close DB connections and fclose () for fopen() connection in class

    0 讨论(0)
  • 2020-12-29 03:30

    So, you probably know what a constructor does. If a constructor sets up, a destructor cleans up. Here's an example from the PHP site:

    <?php
    class my_class {
      public $error_reporting = false;
    
      function __construct($error_reporting = false) {
        $this->error_reporting = $error_reporting;
      }
    
      function __destruct() {
        if($this->error_reporting === true) $this->show_report();
        unset($this->error_reporting);
      }
    ?>
    

    Here's the link to the PHP documentation on the subject.

    0 讨论(0)
  • 2020-12-29 03:37

    It gives the object an opportunity to prepare to be killed. This could mean manual cleanup, state persistence, etc.

    For example, a Model may want to save all of its current properties back into the database.

    Or, a Database object itself might want to close the socket it is using to communicate to a database server.

    0 讨论(0)
提交回复
热议问题