PHP Class Destructors

In this chapter you will learn:

  1. What are PHP Class Destructors
  2. Syntax for Class Destructors
  3. Example - Call __destruct()
  4. Call parent::__destruct().
  5. Deleting Objects

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// j a va2s.  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/*from  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.

Next chapter...

What you will learn in the next chapter:

  1. What are PHP Class Magic Methods
  2. Magic method list
  3. __get()
  4. __set()
  5. __call()
  6. __toString()
Home » PHP Tutorial » PHP Class Definition
Concept for Object Oriented Design
PHP Class Definition
PHP Create Object from Class
PHP Class Properties
PHP Iterating Object Properties
PHP Class Inheritance
PHP Overriding Methods
PHP final Classes and Methods
PHP Abstract Class
PHP Class Access Control Modifiers
PHP Class Constructor
PHP Class Destructors
PHP Class Magic Methods