PHP Class Constructor | Concepts of Constructors, Destructors & types

In this article, we learn PHP Class Constructor object-oriented Concepts of Constructors, Destructors, and types. The constructor is a key part of the PHP oops (object-oriented) conception.
Constructors are special member functions for initial settings of fresh (newly) created object instances from a class. The constructor is known as magic function the magic method starts typically with 2 underscore characters Constructors.
therefore, the constructors are basic building blocks that define the term object and its nature. you’ll be able to say that the Constructors area unit the blueprints for object creation providing values for member functions and member variables.
In PHP4, we have a tendency to create constructor by class name it suggests that the name of the constructor is the same because the class name however in PHP5, it’s been modified to create constructor, it is initialized by keyword.__construct
Syntax:-
- __construct():
1234function _construct(){// its properties by assigning values and initialize the object} - __destruct():
1234function _destruct(){// clean up resources here or destroying the object}
How to define a constructor in PHP
|
1 2 3 4 5 6 7 8 9 |
<?php class Person{ public $name; public $address; public $gender; public function _construct(){ $this->race = "human"; } }?> |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php class Person{ public $name; public $address; public $gender; public function _constuct(){ $this->race = "human"; } } class Employee extends Person{ public function _constuct(){ parent::_construct(); // it will Person class constructor } } $emp1 = new Employee(); // it will call employee and parent class constructor both. ?> |
PHP Class Constructor | Why do we need a constructor?
As we are aware of the constructor, it’s a special function and it automatically called when an object
of a class is instantiated.
therefore in this approach, we are able to take benefits of constructor by using it in our class.
so, We can start a session in the constructor and set up the object before using it, so we don’t have the need to start in every method of the class.
therefore, we can write a few lines of the code segment and start to instantiate an object to call class method then constructor called as the object is instantiated.
so, the line of code segment which is written in the constructor then it is executed automatically.
Constructor with parameters sounds like a regular method because as a result, you’ll able to pass the variable to the constructor as in regular method.
Program | PHP Class Constructor
|
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php class Bird { public $bird_name = "No any birds for now"; public function _construct($bird_name) { $this->bird_name = $bird_name; } } // now the constructor is called automatically because we have initialized the object or class Bird. $bird = new Bird("crow is bird"); echo $bird->bird_name; //Output: Crow is bird ?> |
PHP Class Constructor:- Types of Constructors |
- Default Constructor: it’s no parameters, however, the values to the default constructor may be passed dynamically.
- Parameterized Constructor: It takes the parameters, and additionally you’ll pass different values to the data members.
- Copy Constructor: It accepts the address of the other (opposite) objects as a parameter.
Inheritance: it 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:
To Define Default construction using the function __construct().
|
1 2 3 4 5 6 7 8 9 |
<?php class Person{ public $name; public $address; public $gender; // if _construct() is not defined inside the class then the implicit constructor will //called which is a Default Constructor } ?> |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?PHP class Stock { function Stock() { echo "Its a User-defined Constructor of the class Stock"; } function _construct() { echo "Its a Pre-defined Constructor of the class Stock"; } } $obj= new Stock(); //Output: Its a Pre-defined Constructor of the class Stock ?> |
Parameterized Constructor:
The constructor of the class accepts parameters or arguments.
In the constructor method, you can assign values to the variables during object creation, The -> operator is used to set value for the variables.
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php class Person1{ public $name; public $address; public $gender; public function _construct(){ // parameterized constructor with no-argument $this->race = "human"; } } $perObj1 = new Person1(); // parameterized constructor with no-argument ?> |
|
1 2 3 4 5 6 7 8 9 10 11 |
<?php class Person2{ public $name; public $gender; public function _construct($name){ // parameterized constructor with name argument $this->race = "human"; $this->name = $name; } } $perObj2 = new Person2("john"); // parameterized constructor with name argument ?> |
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php class Employee { Public $name; Public $address; function _construct($name,$address) { // This is initializing the class properties $this->name=$name; $this->place=$address; } function show_details() { echo $this->name." : "; echo "Your address is ".$this->place."\n"; } } $employee_obj= new Employee("Shekhar","Mumbai"); $employee_obj->show_details(); $employee2= new Employee("Saumya","Delhi"); $employee2->show_details(); //output: //Shekhar: Your address is Mumbai //Saumya: Your address is Delhi ?> |
Therefore, the constructors start with 2 underscores and customarily appear like normal traditional PHP functions. Sometimes these constructors are called magic functions beginning with 2 underscores and with some extra functionality than normal methods.
furthermore, After creating an associate object of some class that includes constructors, the content of the constructor is going to be automatically executed.
Copy Constructors
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php class Person1{ public $name; public $gender; public function _construct($name){ // parameterized constructor with name argument $this->race = "human"; $this->name = $name; } public function _clone(){ echo "do something"; } } $perObj2 = new Person1("john"); // parameterized constructor with name argument $perObj3 = clone $perObj2; // copy constructor initialize $perObj3 with the values of $perObj2 echo "<br/>".$perObj3->name; ?> |
Advantages of using Constructors | PHP class Constructor
The Constructors will have as several parameters as required and that they will be outlined with the default arguments.
therefore, the Constructors provides the ability to pass parameters, its help in automatic initialization of the member variables during creation time.
Furthermore, the Constructors will have as several parameters as required and that they will be outlined with the default arguments.
They encourage re-usability avoiding re-initializing whenever the instance of the class is created. You can start the session in the constructor method so that you don’t have to start in all the functions every time.
They can call class functions, member methods, and other constructors even from the parent class.
The __construct() the method always has the public visibility factor.|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php class ParentClass { function _construct() { print "it is a Parent Class Constructor.\n"; } } class ChildClass extends Parentclass { function _construct() { parent::_construct(); print "it is a Child Class Constructor"; } } $obj = new ParentClass(); $obj = new ChildClass(); ?> |
|
1 2 3 |
it is a Parent Class Constructor. it is a Parent Class Constructor. it is a Child Class Constructor. |
Destructor | Characteristics of Destructor:
Destructor is also a special member function, the PHP Destructor method is called just before when an instance of the class is deleted from the memory.
Generally, you can close files, clean up resources, etc in the destructor method. Global objects are destroyed when the code terminates.
furthermore, Global objects are destroyed when the code terminates or full script. Cleaning up of resources before the closing of files takes place in the destructor method or memory release.
_destruct Function
therefore, the Destructors (_destruct ( void): void) are those methods that are called when there is no reference to any object of the class or about to release explicitly or goes out of scope.
Furthermore, they don’t have any type of return value. the Destructors (_destruct) are called before de-allocating memory for during the finish of execution of PHP scripts or an object or as soon as the execution control leaves the block.
The automatic destruction of class objects is handled by PHP Garbage Collector. Let’s take an example.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php class Person { private $fname; private $lname; // Constructor public function _construct($fname, $lname) { echo "Initialising the object...<br/>"; $this->fname = $fname; $this->lname = $lname; } // Destructor public function _destruct(){ // clean up resources or do something else echo "Destroying Object..."; } // public method to show name public function showName() { echo "My Full Name is: " . $this->fname . " " . $this->lname . "<br/>"; } } // creating class object $bryad = new Person("Bryad", "Joshi"); $bryad->showName(); ?> |
|
1 2 3 |
Initialising the object... My Full Name is: Bryad Joshi Destroying Object... |
Therefore, as we will see within the output, the PHP program ends, simply before it, PHP initiates the release of the object created, and therefore, the destructor method is called.
furthermore, the destructor method cannot settle for any argument and is called simply before the object is deleted, that happens either when the PHP script finishes its execution or when no reference exists for the object.
Advantages of destructors:
Destructors provide the chance to objects to free up memory allocation in order that enough space is available for free up resources for other tasks or New objects.
It effectively makes programs run a lot of efficiently and helpfully as they carry out clean up tasks.
The Comparison between __constructors and __destructors:
| CONSTRUCTORS | DESTRUCTORS |
|---|---|
| The function name is _construct(). | The function name is _destruct(). |
| it accepts one or more arguments. | Its void, No arguments are passed. |
| The same name as the class. | The same name as the class with prefix ~tilda. |
| The constructors are used to initialize the instance of a class | The Destructors are used to de-initialize objects already existing to free up memory for new accommodation. |
| that’s can be overloaded. | that’s cannot be overloaded. |
| therefore, constructors used for the purpose to initialize data members of the class. | therefore, destructors used for the purpose make the object perform some task before it is destroyed. |
| this is involved automatically when the object is created. | this is involved automatically when the object is destroyed. |
| therefore, it is called each time a class is instantiated or an object is created. | therefore, it is called automatically at the time of object deletion |
| The Constructors are allocated memory. | The Destructors are deallocated memory. |
| there are Multiple constructors can exist in a class. | there is Only one Destructor can exist in a class |