Destructors are inverse of Constructors in Object Oriented Programming. They are automatically called when an object is no longer in scope. In this article, we will discuss about PHP Destructors.
If you are new to Object Oriented Programming in PHP, you should first read the Introduction article.
Class Destructors
A destructor is a special method which gets automatically called when an object is no longer needed or is no longer in scope. They are not explicitly called and are invoked as soon as the object is destroyed.
Also, like constructors, it is not mandatory to define destructors in PHP. You need to create them only if you want to perform a specific operation while destroying an object.
It is not mandatory to define a destructor as they are automatically called when an object is destroyed.
Example
<?php class Test { public function __construct() { echo 'Object Created'; } public function __destruct() { echo 'Object Destroyed'; } } $testObject = new Test(); ?>
In the above example, the class Test has a constructor and a destructor function. When we create an object it invokes the constructor of the class. After the script is over, the object is no longer in scope and the destructor is automatically called.
OUTPUT: Object Created Object Destroyed
Conclusion
In this article, we discussed PHP Destructors. You can read more about it on the Official PHP Documentation. Additionally, you can learn Object Oriented Concepts in PHP on Concatly.

Vishesh is currently working as an Intermediate Software Engineer with Orion Health, New Zealand. He graduated with a Masters in Information Technology from the University of Auckland in 2021. With more than 4 years of work experience, his expertise includes Java, Python, Machine Learning, PHP, Databases, Design and Architecture.