PHP OOP - Destructor


PHP - The __destruct Function

Destructer is called when an object is corrupted or the text is stopped or exited.

When you create a __destruct () function, PHP will call this function automatically at the end of the script.

Note that destructive work starts with two underscores (__)!

The example below contains the __construct () function automatically created when you create an object from the classroom, and the __destruct () function automatically called at the end of the script:


Example
<?php
class Fruit {
  public $name;
  public $color;

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

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

Another example:


Example
<?php
class Fruit {
  public $name;
  public $color;

  function __construct($name, $color) {
    $this->name = $name;
    $this->color = $color;
  }
  function __destruct() {
    echo "The fruit is {$this->name} and the color is {$this->color}.";
  }
}

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

Tip: As builders and destroyers help reduce code value, they are very useful!