Certainly! Constructors in PHP are special class functions that are automatically executed when an object of a class is instantiated. They are commonly used to initialize the properties of an object.
Basic Constructor:
class Dog {
public $name;
public function __construct() {
$this->name = "Unknown";
}
}
$dog1 = new Dog();
echo $dog1->name; // Outputs: Unknown
Parameterized Constructor:
class Dog {
public $name;
public function __construct($name) {
$this->name = $name;
}
}
$dog1 = new Dog("Buddy");
echo $dog1->name; // Outputs: Buddy
Constructor with default parameters:
class Dog {
public $name;
public $breed;
public function __construct($name = "Unknown", $breed = "Mixed") {
$this->name = $name;
$this->breed = $breed;
}
}
$dog1 = new Dog();
echo $dog1->name . " - " . $dog1->breed; // Outputs: Unknown - Mixed
$dog2 = new Dog("Buddy", "Golden Retriever");
echo $dog2->name . " - " . $dog2->breed; // Outputs: Buddy - Golden Retriever
Constructor in Inheritance:
When using inheritance, the child class can use the parent's constructor. But if the child has its own constructor, it won't automatically call the parent's constructor.
class Animal {
public $type;
public function __construct() {
$this->type = "Unknown";
}
}
class Dog extends Animal {
public $name;
public function __construct($name) {
parent::__construct(); // calling the parent's constructor
$this->name = $name;
}
}
$dog1 = new Dog("Buddy");
echo $dog1->type . " - " . $dog1->name; // Outputs: Unknown - Buddy
Using Static Factory Methods for Multiple Constructors:
As PHP doesn't support multiple constructors, a common approach is to use static factory methods to offer different ways to instantiate an object.
class Circle {
private $radius;
private function __construct($radius) {
$this->radius = $radius;
}
public static function fromRadius($radius) {
return new self($radius);
}
public static function fromDiameter($diameter) {
return new self($diameter / 2);
}
public function getArea() {
return pi() * $this->radius * $this->radius;
}
}
$circle1 = Circle::fromRadius(3);
echo $circle1->getArea();
$circle2 = Circle::fromDiameter(6);
echo $circle2->getArea(); // Outputs the same value as above
UPCET Exam
Click Here
SAAT Exam
Click Here
MHT CET Exam
Click Here
IPU CET Exam
Click Here
KCET Exam
Click Here
COMEDK UG Exam
Click Here
VITEEE Exam
Click Here
BITSAT
Click Here
DSAT: Dayanand Sagar Admission Test
Click Here
Career In Animation in india
Click Here
Merchant Navy Courses in india
Click Here
Interior Design Career in india
Click Here
UGC NET Exam
Click Here
B. Ed Exam
Click Here
AFCAT - Air Force Common Admission Test
Click Here
GATE Exam
Click Here
Joint Entrance Examination (JEE)
Click Here
Common Admission Test (CAT)
Click Here
CDS - Combined Defence Services Exam
Click Here