PHP › OOP
How does inheritance work in PHP using the extends keyword, and how do you call a parent class's constructor or method from within a child class?
IntermediateAnswer
The extends keyword lets a child class inherit the properties and methods of a parent class, automatically gaining access to everything the parent defines as public or protected, and you can explicitly call a parent class's constructor or a specific overridden method using the parent keyword followed by the scope resolution operator, which is commonly used when a child class needs to extend rather than completely replace its parent's behavior.
class Vehicle {
public function __construct(protected string $brand) {}
}
class Car extends Vehicle {
public function __construct(string $brand, private int $doors) {
parent::__construct($brand);
}
}Real-world example A Car class extends a base Vehicle class, calling the parent constructor to properly initialize the shared brand property while also handling its own additional doors property specific to cars.