PHP - Custom Type Class Destructors

Introduction

Destructors are useful for tidying up an object before it's removed from memory.

You create destructor methods in the same way as constructors, except that you use __destruct() rather than __construct():

function __destruct() {
    // (Clean up here)
}

Unlike a constructor, a destructor can't accept arguments.

An object's destructor is called just before the object is deleted.

In each case, the object gets a chance to clean itself up via its destructor before it vanishes.

Demo

<?php

     class Person {
       public function save() {
         echo "Saving this object to the database... \n";
       }//  w ww  .  ja  va2s .c  o  m

       public function __destruct() {
         $this->save();
       }
     }

     $p = new Person;
     unset($p);
     $p2 = new Person;
     die("done! \n");
?>

Result

This Person class contains a destructor that calls the object's save() method to save the object's contents to a database before the object is destroyed.

A new Person object is created and stored in the variable $p.

Next, $p is removed from memory using the built-in unset() function.

Doing this removes the only reference to the Person object, so it's deleted.

Just before it's removed, its __destruct() method is called, displaying the message "Saving this object to the database...".

Next the code creates another Person object, storing it in the variable $p2.