Constructor automatically initializes object properties when an instance is created.
Defined by __construct()
Syntax-
class MyClass {
public function __construct($param1, $param2) { /* constructor code */ }
}
$obj = new MyClass($value1, $value2);Example-
<?php
class Car {
public $brand;
public $color;
public function __construct($brand, $color) {
$this->brand = $brand;
$this->color = $color;
}
}
class ElectricCar extends Car { }
class PetrolCar extends Car { }
$car1 = new ElectricCar("Tesla", "White");
$car2 = new PetrolCar("Toyota", "Blue");
echo $car1->brand . " " . $car1->color . "<br>";
echo $car2->brand . " " . $car2->color;
?>- Car - Parent class
- ElectricCar and PetrolCar - Child classes
- Both child classes inherit brand and color from Car.