Advertisement

Google Ad Slot: content-top

PHP OOP - Destructor


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:

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

Another example:

Example
<?php
class Car {
public $brand;
public $color;
function __construct($brand, $color) {
$this->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