PHP Constructor and Destructor


Both constructor and destructor are PHP’s magic methods.

Constructor:

The constructor function will be automatically called when we instantiate an object when it is being initialized. PHP’s constructor should be defined as:

In PHP 5 and above:

 

 

In PHP 4:

Here “yourclassname” must be your actual class name where you have this constructor.

Destructor:

Destructors are automatically called to destroy the object when the object is no longer used in PHP. In most of the programming languages you need to do this manually, but in PHP, it will be automatically handled by PHP’s Garbage Collector.

Example Class with constructor and destructor:

 

 

 

 

You may also like