PHP Destructor

This tutorial helps you learn about the PHP Destructor.

 

What is PHP Destructor?

The PHP Destructor method is used for destroying the object. It is used just before PHP releases any object from its memory. Generally, the destructor method is used to close files, clean up resources, etc.

 

PHP Destructor Syntax

<?php 

class <CLASS_NAME> {

// destructor 

function __destruct() { 

// clearing the object reference 

}

}

 ?>

 

Example:

<?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("Justin", "Drake");
    $john->showName();
    
?>

Output:

Initialising the object...
My name is: Justin Drake
Destroying Object...

 

As seen in the output above, as the PHP program ends, just before it, PHP prompts the release of the object that has been created, and thus the PHP destructor method is called.

No argument is accepted by the destructor method. It is called just before the object is deleted; this happens either when the PHP script finishes its execution or when no reference exists for an object.