Destructor in PHP

Destructor:

PHP has the ability to create destructor methods. this ability is useful when code has made the last reference to an object or when a script reaches the end.

For example:
<?php
class User
{
function_destruct()
{
//Destructor code goes here
}
}
?>
1.Example for destructor:
<?php
    class Person {
        // first name of person
        private $fname;
        // last name of person
        private $lname;
        
        // Constructor
        public function __construct($fname, $lname) {
            echo "Initialising the object...<br/>"; 
            $this->fname = $fname;
            $this->lname = $lname;
        }
        
        // Destructor
        public function __destruct(){
            // clean up resources or do something else
            echo "Destroying Object...";
        }
        
        // public method to show name
        public function showName() {
            echo "My name is: " . $this->fname . " " . $this->lname . "<br/>"; 
        }
    }
    
    // creating class object
    $john = new Person("Abhishek", "Verma");
    $john->showName();
    
?>
Output:
Initialising the object...
My name is: Abhishek Verma
Destroying Object...
Translate »