PHP OOP - Destructor

In PHP, a destructor is a special method defined within a class that is automatically called when an object is destroyed or goes out of scope. The destructor method is used to perform any cleanup tasks or release resources held by the object before it is removed from memory. The destructor method is always named `__destruct()`.

Here's how you define and use a destructor in PHP:

php
class MyClass {
    // Properties
    public $property1;

    // Constructor
    public function __construct($param1) {
        $this->property1 = $param1;
    }

    // Destructor
    public function __destruct() {
        // Perform cleanup tasks or release resources here
        echo "Object is being destroyed. Cleanup tasks can be performed here.";
    }

// Other methods...
}

In the above example, the `MyClass` has a constructor `__construct()` and a destructor `__destruct()`. When an object of `MyClass` goes out of scope or is explicitly destroyed using the `unset()` function, the destructor is automatically called.


Let's create an object and see how the destructor works:

php
// Creating an object of MyClass
$object = new MyClass('Hello');

// Accessing object property
echo $object->property1; // Output: Hello

// Explicitly destroying the object using unset()
unset($object); // The destructor __destruct() will be called here

When the object is explicitly destroyed using `unset($object)`, or when it goes out of scope (e.g., when the script ends), the destructor `__destruct()` is called, and any cleanup tasks or resource releases specified in the destructor can be performed.


It's important to note that in PHP, objects are automatically destroyed and their destructors are automatically called when they are no longer referenced or when the script execution ends. However, explicitly destroying objects using `unset()` can be useful in certain situations when you want to free up resources immediately rather than waiting for the script to finish.



About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext