Php Constructor

What is Php Constructor?

(i) Php Constructor is a special type of method that is used to initialize the object.
(ii) The Constructor method is a special type of function called __construct within the class body.
(iii) To declare /create a constructor method, use the __construct name (begins with two underscore “__”).
(iv) This method is always “public” even if this attribute is not specified.
(v) The difference from the other functions is that a constructor method is automatically invoked when an object is created.

Rules of creating Constructor
(i) The constructor name must be the same as its class name or use __construct.
(ii) The constructor must have no explicit return type.

Why use constructor?
It is usually used to automatically perform initializations such as property initializations.

Type of Constructor
(i) Default Constructor.
(ii) Parameterized Constructor.
Type-of-Constructor

Default Constructor

When create a object of the class then construct is called, if constructor has not parameter then it is called default constructor.


<?php 
class student  {
	//Define Constructor
	function __construct() {
       echo 'there are 90 students in the class';
    }
}
$stu = new student;
?>

OR


<?php 
class student  {
	//Define Constructor
	function student() {
       echo 'there are 90 students in the class';
    }
}
$stu = new student;
?>

Both Results are same.

Output:- there are 90 students in the class

Parameterized Constructor

If constructor has parameter is called parameterized constructor.


<?php 
class student {

    public $name; // this is initialization
    public $age;

    public function __construct($name,$age) {
      $this->name=$name;
	  $this->age=$age;
    }

    public function introduce() {
        echo "I'm {$this->name} and I'm {$this->age} years old";
    }

  
}
$stu = new student('John',27);
$stu->introduce();
?>
Output:- I’m John and I’m 27 years old

Parent constructor

Parent constructor are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required.


<?php 
class MainClass {
   function __construct() {
       echo "In MainClass constructor!";
   }
}

class ChildClass extends MainClass {
   function __construct() {
       parent::__construct();
       echo "In ChildClass constructor!";
   }
}
$cc_obj=new ChildClass;
?>
Output:- In MainClass constructor!
In ChildClass constructor!