PHP Class Destructors

Description

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

Syntax

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


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

PHP destructors is called when an object is deleted. The destructor method, __destruct(), takes no parameters.

Example


<?PHP/* w w w  .j a  va  2 s. c om*/
class Book {
       public $Name;
       public function say() {
               print "Woof!\n";
       }

       public function __construct($BookName) {
               print "Creating a Book: $BookName\n";
               $this->Name = $BookName;
       }
        public function __destruct() {
               print "{$this->Name} is destructing\n";
        }

}
$aBook = new Book("PHP");
?>

The code above generates the following result.

Call parent::__destruct().

The key difference is that you should call parent::__destruct() after the local code for the destruction. For example:


<?PHP/*w  w  w  .  j a v  a 2  s. c  o m*/
public function __destruct() {
       print "{$this->Name} is no more...\n";
       parent::__destruct();
}
?>

Deleting Objects

Calling unset() on an object will call its destructor before deleting the object.





















Home »
  PHP Tutorial »
    Language Basic »




PHP Introduction
PHP Operators
PHP Statements
Variable
PHP Function Create
Exception
PHP Class Definition