Table of Contents



Introduction

A destructor is called when the object is destroyed or the script ends.

The destructor can do cleanup to free up memory such as releasing a connection to a database or some other resource that you reserved within the class. Because you reserved the resource within the class, you have to release it here, or it will continue to hog memory.

If you create a __destruct() function, PHP will automatically call this function at the end of the script. Similar to the constructor, the __destruct() function starts with two underscores.

The __destruct () Function

The following example has a __construct() function that is automatically called when we create the $object from the User class, and a __destruct() function that is automatically called at the end of the script.

Example

Using a destructor to free up memory.

 1<?php
 2    $object = new User('Betty',29);
 3
 4    class User
 5    {
 6        public $name, $age; // properties
 7
 8        function __construct($name, $age) // constructor
 9        {
10            $this->name = $name;
11            $this->age = $age;
12        }
13
14        function __destruct() {  // destructor
15            echo "The name is " . $this->name . ".<br>";
16            echo "The age is {$this->age}. <br>";
17            echo "Destructor called!";
18        }
19    }
20?>
The name is Betty.
The age is 29.
Destructor called!
Caution

The destructor is called only if objects are created.

Which makes sense since there is no memory to free if no objects have been created in the first place.