__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:

Look at the example class below:

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

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

Comments

Visitor stats.