What is the PHP Destructor function in OOP?

The PHP destructor function is one of the magic methods and it is opposite to the constructor method.

The destructor method runs after all the work of an object is finished.

How to define the destructor method inside a Class?

Here is the syntax to define the destructor method in PHP –

class ClassName{
    function __destruct(){
        // Do what you want
    }
}

Example of the PHP destructor method

The destructor method always runs at the end. In the second example, you can see clearly.

<?php
class MyClass{
    function test(){
        echo "Hello World\n";
    }
    function __destruct(){
        echo "All Done.";
    }
}

$obj = new MyClass();
All Done.

<?php
class MyClass{
    function test(){
        echo "Hello World\n";
    }
    function __destruct(){
        echo "All Done.";
    }
}

$obj = new MyClass();
$obj->test();
Hello World
All Done.