PHP Destructor

PHP Destructors

A Destructor is the exact opposite of a Constructor. It is called when an object is destroyed or when the script is stopped or exited.

If you create a __destruct() function, PHP will automatically execute it at the end of the script lifecycle.


The __destruct() Function

Just like constructors, destructors start with two underscores (__).

Destructors are extremely useful for cleaning up resources. For example, if your object opens a connection to a database or opens a file to read data, you can use the destructor to automatically close that connection or file when the object is no longer needed!

Destructor Example

<?php
class Fruit {
  public $name;

function __construct($name) { $this->name = $name; echo "Constructor called: {$this->name} created!\n"; }

function __destruct() { echo "Destructor called: {$this->name} destroyed!\n"; } }

$apple = new Fruit("Apple"); echo "Doing some other script tasks here...\n"; ?>

Notice how the destructor is called automatically at the very end, without you ever having to trigger it manually!