Constructors in Oops

In this tutorial, you can learn about how to use of PHP constructor and how to call the constructor inside a class



When you create an instance of the class, PHP automatically calls the constructor method.

A constructor allows you to initialize an object’s properties upon creation of the object. It is also called magic function of php, it is called as __construct()

See the below example

 

 



Basically, PHP has Three types of constructor

  1. Non-Parameterized constructor or Default Constructor
  2. Parameterized constructor
  3. Copy constructor

 

Non-Parameterized constructor or Default Constructor

 



It has no parameters, but the values to the default constructor can be passed dynamically.
Example-

 

Parameterized constructor

 

It takes the parameters, and also you can pass different values to the data members.
Example-



Copy constructor

It accepts the address of the other objects as a parameter.

 

Questions asked in PHP Interview on Constructor 

  1.  What is a Constructor?
  2.  How to call the Constructor?
  3.  How many types of Constructor in PHP?
  4.  What is a Destructor?



Tags: , ,