In this tutorial, we will learn about PHP Destructor. The destructor method is totally reverse of the constructor method. PHP destructor does not return any value. In case we create __destructor function in class, PHP will automatically call the destructor function if there are no other references to a particular object or at the end of the script.
Please Note, that the desructor function starts with two underscores (__). for e.g. __destruct()
Here an example program to show how to define destructor in PHP.
<?php
class Example {
//defing a constructor
function __construct() {
echo "This is constuctor method.<br>";
}
//defing a normal method
function show(){
echo "This is show method.<br>";
}
//defing a destructor
function __destruct() {
echo "The is destructor method.<br>";
}
}
$obj = new Example();
$obj->show();
$obj->show();
$obj->show();
?>
The destructor will be called even if script execution is stopped using exit() or die() function.
Difference b/w Constructor and PHP Destructor:
| Constructor | Destructor |
|---|---|
| It Allocates Memory | It Deallocates Memory |
| Get called at the time of class is instantiated | Get called at the time of deletion of the object |
| Name of function is _construct(). | Name of function is _destruct() |
| Can accept parameters | Can not accept parameters |
| Constructors can be overloaded | Destructors can not be overloaded |
Parvesh Sandila is a results-driven tech professional with 8+ years of experience in web and mobile development, leadership, and emerging technologies.
After completing his Master’s in Computer Applications (MCA), he began his journey as a programming mentor, guiding 100+ students and helping them build strong foundations in coding. In 2019, he founded Owlbuddy.com, a platform dedicated to providing free, high-quality programming tutorials for aspiring developers.
He then transitioned into a full-time programmer, where his hands-on expertise and problem-solving skills led him to grow into a Team Lead and Technical Project Manager, successfully delivering scalable web and mobile solutions. Today, he works with advanced technologies such as AI systems, RAG architectures, and modern digital solutions, while also collaborating through a strategic partnership with Technobae (UK) to build next-generation products.
