This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

7.4 PHP Destructor

    • A destructor is called when the object is destructed or the script is stopped or exited.
    • If you create a __destruct() function, PHP will automatically call this function at the end of the script.
    • Notice that the destruct function starts with two underscores (__)!
    • 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:
    Example 1: PHP Destructor part 1
    <?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 2: PHP Destructor part 2
    <?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");
    ?>
    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon

    Module 6 quiz