Method Overriding
Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 23 of 91.
Sometimes the inherited method from a parent class doesn't quite fit what the child class needs. Method overriding lets a child class provide its own implementation of a method that already exists in the parent.
To override a method, simply define a method in the child class with the same name as the parent's method:
<?php
class Animal {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function speak() {
return "$this->name makes a sound";
}
}
class Cat extends Animal {
public function speak() {
return "$this->name says meow";
}
}
$cat = new Cat("Whiskers");
echo $cat->speak();
Output:
Whiskers says meowThe Cat class completely replaces the parent's speak() method with its own version. When you call speak() on a cat object, PHP uses the child's implementation.
You can also extend the parent's behavior by combining parent:: with your own logic:
<?php
class Dog extends Animal {
public function speak() {
return parent::speak() . " - woof woof!";
}
}
$dog = new Dog("Rex");
echo $dog->speak();
Output:
Rex makes a sound - woof woof!Key Point: Method overriding allows child classes to customize inherited behavior. You can completely replace a method or use parent:: to build upon the original implementation.
Challenge
EasyLet's build a notification system that demonstrates how child classes can completely replace or extend parent methods through method overriding.
You'll create three files that work together to send different types of notifications, each with its own unique behavior:
Notification.php— Define aNotificationclass that serves as the base for all notification types. It should have a public$recipientproperty and a constructor that accepts and sets the recipient. Include asend($message)method that returns"Sending to [recipient]: [message]".UrgentNotification.php— Define anUrgentNotificationclass that extendsNotification. Include the Notification file at the top. This class should completely override thesend($message)method to return"URGENT to [recipient]: [message]!!!"— notice the "URGENT" prefix and the exclamation marks at the end. This demonstrates fully replacing the parent's behavior.LoggedNotification.php— Define aLoggedNotificationclass that extendsNotification. Include the Notification file at the top. This class should overridesend($message)but build upon the parent's implementation: callparent::send($message)and append" [logged]"to the result. This demonstrates extending rather than replacing behavior.
In main.php, include all three notification class files. You'll receive two inputs: the recipient name and the message to send. Create one instance of each notification type (all using the same recipient), then call send() with the message on each one. Print each result on its own line in this order: regular notification, urgent notification, then logged notification.
This challenge shows both approaches to method overriding — the UrgentNotification completely replaces the parent's logic with its own formatting, while LoggedNotification uses parent:: to keep the original behavior and add to it.
Cheat sheet
Method overriding allows a child class to provide its own implementation of a method inherited from a parent class.
To override a method, define a method in the child class with the same name as the parent's method:
<?php
class Animal {
public function speak() {
return "makes a sound";
}
}
class Cat extends Animal {
public function speak() {
return "says meow";
}
}
The child class completely replaces the parent's method implementation. When called on a child object, PHP uses the child's version.
To extend the parent's behavior instead of replacing it, use parent:: to call the parent method and add your own logic:
<?php
class Dog extends Animal {
public function speak() {
return parent::speak() . " - woof woof!";
}
}
This combines the parent's original behavior with additional functionality from the child class.
Try it yourself
<?php
require_once 'Notification.php';
require_once 'UrgentNotification.php';
require_once 'LoggedNotification.php';
// Read input
$recipient = trim(fgets(STDIN));
$message = trim(fgets(STDIN));
// TODO: Create one instance of each notification type (all using the same recipient)
// TODO: Call send() with the message on each notification
// Print each result on its own line in this order:
// 1. Regular notification
// 2. Urgent notification
// 3. Logged notification
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern