extends, parent::)Inheritance allows a child subclass to inherit all public and protected properties and methods from a parent superclass using the extends keyword. Child classes can extend functionality, add new methods, or override parent behaviors using parent::.
flowchart TD
A["Parent Class (Vehicle)"] --> B["Child Subclass 1 (Car)"]
A --> C["Child Subclass 2 (ElectricCar)"]
A --> A1["#speed, +accelerate()"]
B --> B1["+fuelType, +refuel()"]
C --> C1["+batteryCapacity, +chargeBattery()"]
extends: Establishes inheritance link.parent::__construct(): Calls parent constructor from child class.final: Prevents a class from being extended or a method from being overridden.<?php
declare(strict_types=1);
class Vehicle
{
public function __construct(
protected string $brand,
protected int $speed = 0
) {}
public function accelerate(int $increment): void
{
$this->speed += $increment;
echo "{$this->brand} accelerated to {$this->speed} km/h.
";
}
public function getInfo(): string
{
return "Brand: {$this->brand} | Current Speed: {$this->speed} km/h";
}
}
class ElectricCar extends Vehicle
{
public function __construct(
string $brand,
public int $batteryCapacityKWh
) {
// Call parent constructor
parent::__construct($brand);
}
// Overriding parent getInfo() method
public function getInfo(): string
{
return parent::getInfo() . " | Battery: {$this->batteryCapacityKWh} kWh";
}
}
$ev = new ElectricCar("Tesla", 85);
$ev->accelerate(50);
echo $ev->getInfo() . "
";
parent::__construct() in Child Constructors: Ensures parent initialization logic runs cleanly.final to Prevent Unwanted Inheritance: Mark classes or critical security methods as final class UserSecurity to prevent overriding.Write a class Manager extends Employee that calls parent::__construct($name, $salary) inside its constructor!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.
You've completed this section! Take a quick 5-question quiz to check your understanding.