In Php OOPS, Constructor is a special member function which is created by the __construct() keyword.
__construct() is automatically called when we create instance of the class.
__construct() is a “Magic” Method used to define a Constructor.
The first method of any class is “Constructor method“.
__construct() can take multiple parameters.
Example 1:
<?php
class Animal
{
private $name;
// constructor definition
public function __construct($animal_name)
{
$this->name = $animal_name;
}
}
$animal = new Animal("Indian Tiger");
echo $animal->name;
?>
------------ ****** ------------
OUTPUT:
Indian Tiger
Example 2:
<?php
class BaseClass {
public static $a=10;
public function __construct() {
echo "Calling parent class constructor"."<br>";
}
}
class SubClass extends BaseClass {
public function __construct($a) {
echo "Calling child class constructor value = ".$a."<br>";
}
}
class SubClass1 extends SubClass {
public function __construct($a,$b) {
echo "Calling child class 1 constructor ".$a."======".$b."<br>";
}
}
$obj1 = new SubClass1(2,5);
?>
------------ ****** ------------
OUTPUT:
Calling child class 1 constructor “2”======”5
Note : If we want to called “Parent Class Constructor” in child class ,then we can achieved it by parent keyword followed by Scope Resolution operator(::).
i.e : parent ::__construct().
<?php
class BaseClass {
public static $a=10;
public function __construct() {
echo "Calling parent class constructor"."<br>";
}
}
class SubClass extends BaseClass {
public function __construct() {
// Call to parent class constructor
parent::__construct();
echo "Calling child class constructor"."<br>";
}
}
$obj = new BaseClass();
$obj1 = new SubClass();
?>
------------ ****** ------------
OUTPUT:
Calling parent class constructor.
Calling parent class constructor.
Calling child class constructor.