Back to course

Inheritance: Extending Classes

PHP: The Complete 0 to Hero Bootcamp

36. Inheritance: Extending Classes

Inheritance allows one class (Child Class) to reuse the properties and methods defined in another class (Parent Class). This is achieved using the extends keyword.

Parent and Child Classes

php

speed += $amount; } public function getSpeed() { return $this->speed; } } class Truck extends Vehicle { // Child Class / Derived Class public function loadCargo() { echo "Truck is loading cargo...\n"; } // The Truck class inherits accelerate() and getSpeed() } $myTruck = new Truck(); $myTruck->loadCargo(); $myTruck->accelerate(50); echo "Current speed: " . $myTruck->getSpeed(); // Output: 50 ?>

Overriding Methods

A child class can define a method with the exact same name as a parent method. This overrides the parent's implementation for that specific child class instance.

php

accelerate(30); // Output: Shifting gear... Current speed: 30 ?>
  • We use parent::methodName() to call the parent's original method from within the overridden child method.