Member-only story
What is Constructor in PHP
2 min readAug 13, 2022
- Constructor in PHP is declared with __construct() function using double underscore.
- When we define a class, we declare individual set methods to access the particular property of that class but if we initialize a constructor inside the parent class, then no need to include set methods.
- It helps us to reduce the number of set methods to declare for each public property of the class.
- PHP will automatically call the __construct() function as soon as the creation of object of the parent class.
- It refers to the current object of your parent class.
- Also, we can create multiple objects of the parent class and access the properties passed inside the construct function with the help of each created object.
- We don’t need to initialize functions every time we declare public properties. Instead, we can use the constructor to do the same. So, the constructor is very useful in such cases.
- The constructor plays an important role in object-oriented programming. If you want to make your code easy and simple then you can use a constructor.
- We can pass the public properties of a class inside the __construct() function one by one as shown below.
Also read, OOPS concepts in PHP with real-time examples