Destructor

PHP (like Java, but unlike C++) has automatic garbage collection.

 

Unless otherwise explicitly carried out, objects are automatically destroyed at the end of the script they were created in.

 

In some cases, it might sometimes be useful to specifically carry out a task when an object  is destroyed, say to close a database connection.

 

Accordingly, the destructor is a magic method that is automatically called when an object is destroyed, e.g. at the end of the script.

 

Syntax:

public function __destruct() {

… code goes here…

 }

 

(*note: magic methods start with a double underscore __ and will be discussed below)

 

A class showing a destructor being automatically called at the end of the script:

Save & refresh browser:

An instance of the the ‘Dog’ class has been instantiated!
The script ends here.
Yalp!! The ‘Dog’ object has been destroyed!

 

It can be seen that the destructor was called after the last command in the script, i.e. when the script ended.

Leave a Reply