__destruct in PHP 5

-

Introduction

A Destructor in PHP is a method that gets called when an object of a class is destroyed.

There are a number of reasons why the ‘__destruct’ method would be called. Firstly is if the object goes out of scope meaning that the object can not longer be used by the accessed by program, secondly when the program has finished and finally if you set the class object to null

Usage

Using a destructor is easy, its done using a pre-defined method name: 

<?php
  public function __destruct() { 
    // code here 
  }
?>

Look at the example class below: 

<?php
  class WebDeveloper {
    public $name;
    public function __construct($name) {
      $this->name = $name
    }
    public function __destruct() {
      unsent($this->$name);
    }
  }
?>

Now when you instantiate the web developer class object you must parse one parameter to the class otherwise PHP will throw an error

<?php
  $developer = new WebDeveloper('jordizle');
?>

Now the class attributes have been set. If I was to set the ‘WebDeveloper’ object to null the destruct method will be automatically called: 

<?php
  $developer = null;
?>

Your comments.