Use of PHP __construct function (PHP Constructor)

By informerfrk

Like many other programming languages, we can also define and use the constructor. The constructor in PHP is so useful and used in both small and large projects.

Previously, in PHP the constructor was defined by creating a method with the same method where the name of the method was same as the class name. But now it is depreciated way of creating constructor inside a class. Now the constructor method is defined with “__construct()”.

Before I further discuss, I want to make it clear to you that methods in PHP are nothing but functions that are inside a class. Whenever you create a function inside a class, it can be called method.

Suppose you have created a PHP class and inside the class, you have created a constructor. After that, you have created an object of the class. In the time of creating the object, the constructor will be called. See the example below:

<?php

class MyClass
{
  
  function __construct()
  {
    echo "This is from constructor";
  }
}

$obj = new MyClass();

?>

In the above example code, we have created a class and name it MyClass. After that, we have created an object of this class. Now if you run the code, you will see the output that is given below:

This is from constructor

From the output, it is very clear that the constructor called immediately after you create an object of the class.

Now see another example of PHP constructor:

<?php

class MyClass
{
  
  function __construct($i)
  {
    echo $i;
  }
}

$obj = new MyClass(5);

?>

In the above code, we have taken an argument to the constructor function of the class MyClass. Now if you run the code you will see the output:

5

That means you can give the argument to the PHP constructor in the time of creating an object. This is one of the most useful features of using the constructor and many PHP project use this feature.

Now in the below code, you can see the usage of PHP __construct function with a method inside the class:

<?php

class MyClass
{
  private $num;
  function __construct($i)
  {
    $this->num = $i;
  }
  public function fun() 
  {
      echo $this->num;
  }
}

$obj = new MyClass(5);
$obj->fun();

?>

In the above code, you can see that we have declared a private variable and we pass the argument inside that variable. After that, we display that variable through another method fun().


 

Leave a Reply

Your email address will not be published. Required fields are marked *