PHP | Constructors and Destructors - GeeksforGeeks

04 Jul, 2021
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:  
php
<?PHPclass Tree{    function Tree()    {        echo "Its a User-defined Constructor of the class Tree";    }     function __construct()    {        echo "Its a Pre-defined Constructor of the class Tree";    }} $obj= new Tree();?>
Output:  
Its a Pre-defined Constructor of the class Tree
Parameterized Constructor: The constructor of the class accepts arguments or parameters. The -> operator is used to set value for the variables. In the constructor method, you can assign values to the variables during object creation.Program:  
php
<?php class Employee{         Public $name;     Public $position;     function __construct($name,$position)     {        // This is initializing the class properties        $this->name=$name;        $this->profile=$position;      }        function show_details()    {        echo $this->name." : ";        echo "Your position is ".$this->profile."\n";    }}     $employee_obj= new Employee("Rakesh","developer");$employee_obj->show_details();     $employee2= new Employee("Vikas","Manager");$employee2->show_details(); ?>
Output:  
Rakesh : Your position is developer
Vikas : Your position is Manager
Constructors start with two underscores and generally look like normal PHP functions. Sometimes these constructors are called as magic functions starting with two underscores and with some extra functionality than normal methods. After creating an object of some class that includes constructor, the content of constructor will be automatically executed.Note: If the PHP Class has a constructor, then at the time of object creation, the constructor of the class is called. The constructors have no Return Type, so they do not return anything not even void.Advantages of using Constructors:  
Constructors provides the ability to pass parameters which are helpful in automatic initialization of the member variables during creation time .
The Constructors can have as many parameters as required and they can be defined with the default arguments.
They encourage re-usability avoiding re-initializing whenever instance of the class is created .
You can start session in constructor method so that you don’t have to start in all the functions everytime.
They can call class member methods and functions.
They can call other Constructors even from Parent class.
Note : The __construct() method always have the public visibility factor. Program:  
php
<?phpclass ParentClass    {        function __construct()        {            print "Parent class constructor.\n";        }    } class ChildClass extends Parentclass    {        function __construct()        {            parent::__construct();            print "Child Class constructor";        }    }$obj = new ParentClass();$obj = new ChildClass(); ?>
Output  
Parent class constructor.
Parent class constructor.
Child Class constructor
Note: Whenever child class object is created, the constructor of subclass will be automatically called.Destructor: Destructor is also a special member function which is exactly the reverse of constructor method and is called when an instance of the class is deleted from the memory. Destructors (__destruct ( void): void) are methods which are called when there is no reference to any object of the class or goes out of scope or about to release explicitly. They don’t have any types or return value. It is just called before de-allocating memory for an object or during the finish of execution of PHP scripts or as soon as the execution control leaves the block. Global objects are destroyed when the full script or code terminates. Cleaning up of resources before memory release or closing of files takes place in the destructor method, whenever they are no longer needed in the code. The automatic destruction of class objects is handled by PHP Garbage Collector. 
~ ClassName()
{

}
Note: The destructor method is called when the PHP code is executed completely by its last line by using PHP exit() or die() functions.
Program:  
php
<?phpclass SomeClass    {         function __construct()        {            echo "In constructor, ";            $this->name = "Class object! ";        }         function __destruct()        {            echo "destroying " . $this->name . "\n";        }    }$obj = new Someclass(); ?>
Output:  
In constructor, destroying Class object! 
Note: In the case of inheritance, and if both the child and parent Class have destructors then, the destructor of the derived class is called first, and then the destructor of the parent class.  
Advantages of destructors:  
Destructors give chance to objects to free up memory allocation , so that enough space is available for new objects or free up resources for other tasks.
It effectively makes programs run more efficiently and are very useful as they carry out clean up tasks.
Comparison between __constructors and __destructors: 
 
Conclusion: In the real programming world, Constructors and Destructor methods are very useful as they make very crucial tasks easier during coding. These encourage re-usability of code without unnecessary repetition. Both of them are implicitly called by compiler even they are not defined in the class. 
anikaseth98
PHP-OOP
PHP
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
PHP in_array() Function
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
Comparing two dates in PHP
PHP | strval() Function