PHP
Method override
Learn to override a parent method in a child class.
What is method override?
The child class can redeclare a method from the parent with the same name. This is called method override.
When you override, the child's version of the method is called on child instances. The parent's version is not lost, but it is not used directly. This enables "same interface, different behavior".
For example, Vehicle::describe() might return "Vehicle: ..." while Car::describe() changes the output of the same method. The child customizes behavior freely.
Override combined with parent::
When overriding, you don't have to ignore the parent's method completely. You can call the parent's version with parent::method() and extend its result.
For example, inside Car::describe(), writing return parent::describe() . " (4 wheels)"; uses the parent's logic and adds extra info. This is the extension pattern, the most common use of override.
Common logic stays in the parent and the child only adds the difference, so code duplication is avoided.
Exercise Override the describe method in Car
In this lesson Vehicle's describe() method returns "Vehicle: " + brand. You will derive Car from Vehicle and override the describe() method. Inside the overridden method, call parent::describe() and append " (4 wheels)". Create a Volvo Car instance and print the describe() output.
Show example solution
:describe() and append " (4 wheels)".
Example solution:
<?php
class Vehicle {
public string $brand;
public function __construct(string $brand) {
$this->brand = $brand;
}
public function describe(): string {
return "Vehicle: " . $this->brand;
}
}
class Car extends Vehicle {
public function describe(): string {
return parent::describe() . " (4 wheels)";
}
}
$car = new Car("Volvo");
echo $car->describe();
Test yourself
-
Which of the following is an example of override?
- Adding a new property to the child
- Deleting the parent method
- Copying the parent class
- Redefining a method in the child with the same name as the parent's
Show answer
Redefining a method in the child with the same name as the parent's — Correct; override is redefining a parent method in the child with the same name.
-
Complete the override with parent:: call
public function describe(): string {
return parent::____() . " (4 wheels)";
}
Show answer
public function describe(): string {
return parent::describe() . " (4 wheels)";
}
-
Match concepts related to override
- Method override
- Redefining with the same name
- parent::method()
- Calling the parent's method
- Extension pattern
- Adding to the parent's result
- Child version is called
- On overridden methods
Next lesson: protected property and method