oursolutionarchitectoursolutionarchitect

PHP | Constructors and Destructors


Constructors are special member functions for initial settings of newly created object instances from a class, which is the key part of the object-oriented concept in PHP5.
Constructors are the very basic building blocks that define the future object and its nature. You can say that the Constructors are the blueprints for object creation providing values for member functions and member variables.
Once the object is initialized, the constructor is automatically called. Destructors are for destroying objects and automatically called at the end of execution.
In this article, we are going to learn about object-oriented concepts of constructors and destructors. 
Both are special member functions of any class with different concepts but the same name except destructors are preceded by a ~ Tilda operator.
Syntax: 
 

  • __construct(): 
     
function __construct()
       {
       // initialize the object and its properties by assigning 
       //values
       }

 

  • __destruct(): 
     
function __destruct() 
       {
       // destroying the object or clean up resources here 
       }

Note: The constructor is defined in the public section of the Class. Even the values to properties of the class are set by Constructors.
Constructor types: 
 

  • Default Constructor:It has no parameters, but the values to the default constructor can be passed dynamically.
  • Parameterized Constructor: It takes the parameters, and also you can pass different values to the data members.
  • Copy Constructor: It accepts the address of the other objects as a parameter.

Inheritance: As Inheritance is an object-oriented concept, the Constructors are inherited from parent class to child class derived from it. Whenever the child class has constructor and destructor of their own, these are called in order of priority or preference. 
Pre-defined Default Constructor: By using function __construct(), you can define a constructor.
Note: In the case of Pre-defined Constructor(__construct) and user-defined constructor in the same class, the Pre-defined Constructor becomes Constructor while user-defined constructor becomes the normal method.
Program: