Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Destructor

PHP – The __destruct Function

A destructor is invoked when an object is destroyed or when the script is stopped or exited.

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

Note that the destructor function begins with two underscores (__).

In the example below, the __construct() function is automatically called when an object is created from a class, and the __destruct() function is 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: Constructors and destructors are very useful for reducing code by automating initialization and cleanup tasks!