PHP Constructor and Destructor Example -

PHP Constructor and Destructor

PHP Summer Training/Internship with 2 Live Projects in Noida Fee is only 5500/-Click here to Book Your Seat.


PHP Constructor and Destructor

PHP Constructor, If a class name and function name will be similar in that case function is known as constructor.

Constructor is special type of method because its name is similar to class name.

Constructor automatically calls when object will be initializing.


This is user defined constructor of class A
This is test method of class A

Note : Here we have called testA() method but we didn’t call A() method because it automatically called when object is initialized.


Predefine Constructor

PHP introduce a new functionality to define a constructor i.e __construct().

By using this function we can define a constructor.

It is known as predefined constructor. Its better than user defined constructor because if we change class name then user defined constructor treated as normal method.

Note: if predefined constructor and user defined constructor, both define in the same class, then predefined constructor treat like a Constructor while user defined constructor treated as normal method.



This is predefined constructor

Initialize class property using constructor(Value entered by users)


sum of given no=1500
enter your first number
enter your second number


Parametrized Constructor

Welcome shashi… Your profile is developer
Welcome pankaj… Your profile is Tester


Destructor in PHP

The Destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

Destructor automatically call at last.

Note : _ _destruct() is used to define destructor.

object is initializing their properties
Now works is going
after completion the work, object destroyed automatically

Keep Updating yourself