PHP
Inheritance with extends
Learn to inherit from a class with the extends keyword.
Inheritance with extends
Transferring all members (properties and methods) of a class to another class is called inheritance. The existing class is the parent, the new class is the child.
In PHP, you use the extends keyword to inherit. The child class can directly access all public and protected members of the parent. This avoids code duplication and lets you build new behavior on top of existing classes.
For example, to derive a Dog class from an Animal class, you write class Dog extends Animal.
An inheritance example
Let's see inheritance with a concrete example. A Vehicle class holds the brand property and a describe() method that are common to all vehicles.
When the Car class inherits from Vehicle, it does not redeclare brand or describe(); it uses them directly. On top of that, it can add its own method (e.g. honk()).
Both describe() and honk() can be called. This is an "is-a" relationship: a Car is a Vehicle.
Exercise Make Car inherit from Vehicle
In this lesson the Vehicle class is provided. You will derive the Car class from Vehicle with extends. Add a honk() method inside Car that returns "Honk!". Create a Car instance with brand Volvo and print the describe() and honk() outputs.
Show example solution
Derive the new class with class Car extends Vehicle { ... }. Inside honk(), write return "Honk!";.
Example solution:
<?php
class Vehicle {
public string $brand;
public function __construct(string $brand) {
$this->brand = $brand;
}
public function describe(): string {
return "Brand: " . $this->brand;
}
}
class Car extends Vehicle {
public function honk(): string {
return "Honk!";
}
}
$car = new Car("Volvo");
echo $car->describe() . "\n";
echo $car->honk() . "\n";
Test yourself
-
What does the extends keyword do?
- Copies a class's properties but changes them
- Terminates and deletes a class
- Transfers a class's public/protected members to another class
- Assigns a default value to a variable
Show answer
Transfers a class's public/protected members to another class — Correct; extends passes the parent's public/protected members to the child.
-
Complete the extends pattern
class Dog ____ Animal {
public function bark(): string {
return "Woof!";
}
}
Show answer
class Dog extends Animal {
public function bark(): string {
return "Woof!";
}
}
-
Match concepts with their descriptions
- Parent class
- Class being inherited from
- Child class
- Class that inherits
- extends
- Inheritance keyword
- is-a relationship
- A child is a parent
Next lesson: Accessing parent with parent::