HOME HTML EDITOR C JAVA PHP

PHP OOP Destructor

A destructor is called when an object is destructed or the script is stopped or exited. If you create a __destruct() function, PHP will automatically call this function at the end of the script's execution.

1. The Purpose of a Destructor

While constructors are used to initialize an object, destructors are used to clean up. This is commonly used to close database connections, close open files, or write log messages before the object is removed from memory.

2. Syntax of __destruct()

Like the constructor, the destructor starts with two underscores (__). It does not take any arguments.

<?php
class Fruit {
  public $name;

  function __construct($name) {
    $this->name = $name;
  }

  // The Destructor
  function __destruct() {
    echo "The fruit is {$this->name}.";
  }
}

$apple = new Fruit("Apple");
?>

3. How it Works

In the example above, the destructor is called automatically at the very end of the script. Even though we didn't explicitly call a method to print the name, the __destruct() function executed as soon as the script finished and the $apple object was destroyed.

4. Explicitly Destroying an Object

You don't always have to wait for the script to end. You can trigger the destructor immediately by setting the object variable to null or using the unset() function.

<?php
$apple = new Fruit("Apple");
unset($apple); // Destructor is called right here!

echo "This will print after the destructor message.";
?>

5. Key Differences

Feature Constructor (__construct) Destructor (__destruct)
Timing Called when object is created. Called when object is destroyed.
Arguments Can accept parameters. Cannot accept parameters.
Usage Setting up initial values. Closing resources/cleaning up.
Tip: Destructors are incredibly helpful in heavy applications to ensure that database connections are not left "hanging" open, which can slow down the server.