Advertisement

Google Ad Slot: content-top

PHP OOP - Destructor

~1 min read · PHP
On this page

A destructor is a special method in a class that is automatically called when an object is destroyed or goes out of scope


In PHP, destructors are defined using the __destruct() method.


 Syntax of a Destructor


class ClassName {
  public function __destruct() {
    // Code to be executed when the object is destroyed
  }
}



The example below has a __construct() function that is automatically called when you create an object from a class, and a __destruct() function that is automatically called at the end of the script:

brand = $brand; } function __destruct() { echo "The car brand is {$this->brand}."; } } $car = new Car("Honda"); ?>
Try it yourself

Another example:

Example
brand = $brand; $this->color = $color; } function __destruct() { echo "The car brand is {$this->brand} and the color is {$this->color}."; } } $car = new Car("Honda", "Blue"); ?>
Try it yourself