PHP Class Destructors
In this chapter you will learn:
- What are PHP Class Destructors
- Syntax for Class Destructors
- Example - Call __destruct()
- Call parent::__destruct().
- 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:
Home » PHP Tutorial » PHP Class Definition