Hello! Welcome back to our module on Advanced OOP Concepts.
In the last lesson, we explored inheritance, learning how a child class can inherit properties and methods from a parent class using the extends keyword. We saw how this creates an "is-a" relationship and helps us write reusable, organized code. We also saw a specific use of the parent:: keyword to call a parent's constructor (parent::__construct()).
Today, we'll expand on that idea. What happens when a child class needs to provide a different version of a method it inherited? This is called method overriding. You'll learn how to replace a parent method with a new implementation in the child class and, crucially, how to extend—not just replace—the parent's logic using the parent:: keyword.
This skill is essential for building specialized classes that modify or enhance the behavior of their parents, a common requirement in complex web applications.
1. What is Method Overriding?
Method overriding allows a child class to provide its own specific implementation for a method that is already defined in its parent class. When an object of the child class calls that method, PHP will execute the child's version, not the parent's.
For example, imagine a User class with a getProfilePage() method that returns a standard user profile URL. An AdminUser child class might override this method to return a URL for a more detailed, administrative profile page.
Let's start with a foundational example from the official PHP documentation.
The PHP manual provides a concise, authoritative explanation of method overriding. Pay close attention to the code example.
In this resource, locate the section under the extends keyword. Read the paragraph that begins 'The inherited constants, methods, and properties can be overridden...' and study 'Example #10 Simple Class Inheritance'. Notice how ExtendClass redefines the displayVar() method.
As you saw in the example, both SimpleClass and ExtendClass have a method named displayVar(). When we call $extended->displayVar(), the version in ExtendClass is executed because the object ($extended) is an instance of ExtendClass. This is method overriding in its simplest form: replacing the parent's behavior.
2. Extending Parent Behavior with parent::
More often than not, you don't want to completely replace a parent's method. Instead, you want to add to it. You might want to run the parent's logic first and then add some child-specific logic.
This is where the scope resolution operator (::) combined with the parent keyword becomes incredibly powerful. You've already used parent::__construct() to call a parent constructor; you can use the same syntax to call any public or protected method from the parent class.
parent::methodName();
Let's watch a video that demonstrates this. The instructor will override a getPropertyTwo method, but instead of just replacing it, he'll call the parent's version and then add to its result.
Inheritance for beginners - OOP in PHP | Part 6
This video from The Codeholic provides a clear, practical demonstration of extending a parent method.
Watch the segment from 03:49 to 05:00. Focus on this line: $result = parent::getPropertyTwo();. See how it allows the child class to get the value from the parent and then modify it before returning.
This pattern is extremely common. For example, a child class might override a save() method to first call parent::save() to save the core data to the database, and then run its own code to save additional, child-specific data.
Let's look at another practical example of this, this time overriding a constructor.
Inheritance for beginners - OOP in PHP | Part 6
Continuing with the same video, let's see a more real-world example involving Person and Employee classes. This reinforces the concept we touched on in our last lesson.
Watch from 09:37 to 10:56. Notice how the Employee constructor takes all the necessary arguments, passes the relevant ones up to the Person constructor using parent::__construct(), and then handles its own unique $salary property.
3. Rules and Important Considerations
When overriding methods, there are a few important rules you must follow to avoid errors.
Visibility Rules
You cannot make an inherited method more restrictive (less visible) than it was in the parent class.
- A
publicmethod in the parent can be overridden aspublic. - A
protectedmethod in the parent can be overridden asprotectedorpublic. - A
privatemethod cannot be overridden because it's not visible to the child class at all.
Trying to change a public method to protected in a child class, for example, will result in a fatal error.
Signature Compatibility
The "signature" of a method includes its name, its parameters, and its return type. When you override a method, the child's method signature must be compatible with the parent's.
The PHP manual provides the definitive rules on what makes a method signature 'compatible.' Understanding this is key to avoiding common errors.
Read the section titled 'Signature compatibility rules'. The main takeaway is that you can't make breaking changes. You can add new optional parameters, but you cannot remove parameters or make an optional parameter mandatory.
A Note on Method Overriding vs. Overloading
You may have heard the term "method overloading" in other programming languages. This typically means having multiple methods with the same name but different parameters within the same class.
PHP does not support method overloading in this way. What we are doing here is specifically method overriding: redefining a method in a child class with the same signature. This distinction is important.
Hands-on Practice
Let's apply what you've learned. We'll build on the Post and Article classes from our last lesson.
You have a Post class with a method to generate a title tag for HTML. The Article class, being more specific, should add the author's name to that title tag.
-
Modify the Parent
PostClass:- Start with the
Postclass from the previous lesson (it should haveprotectedproperties for$titleand$content, and a constructor). - Add a
publicmethod namedgetTitleTag()that returns an HTML<h1>tag containing the post's title. For example:<h1>PHP Inheritance Explained</h1>.
- Start with the
-
Override the Method in the
ArticleClass:- Start with the
Articleclass thatextends Post(it has an additional$authorproperty). - Override the
getTitleTag()method. - Inside the new
getTitleTag()method, first call the parent'sgetTitleTag()method to get the<h1>tag. - Append the author's name to the result, perhaps in a
<span>tag. The final output should look something like:<h1>PHP Inheritance Explained</h1><span>By: Alex</span>. - Return this new, combined string.
- Start with the
-
Instantiate and Test:
- Create a new
Articleobject. echothe result of calling thegetTitleTag()method on yourArticleobject.
- Create a new
Click to see a possible solution
<?php
// 1. Parent Class
class Post
{
protected string $title;
protected string $content;
public function __construct(string $title, string $content)
{
$this->title = $title;
$this->content = $content;
}
// New method in the parent
public function getTitleTag(): string
{
return "<h1>{$this->title}</h1>";
}
public function display(): void
{
echo $this->getTitleTag();
echo "<p>{$this->content}</p>";
}
}
// 2. Child Class
class Article extends Post
{
public string $author;
public function __construct(string $title, string $content, string $author)
{
parent::__construct($title, $content);
$this->author = $author;
}
// Overriding the parent method
public function getTitleTag(): string
{
// Call the parent method to get the base H1 tag
$titleTag = parent::getTitleTag();
// Add the author information
$authorTag = "<span>By: {$this->author}</span>";
// Return the combined result
return $titleTag . $authorTag;
}
}
// 3. Instantiate and Test
$myArticle = new Article(
'PHP Method Overriding',
'Overriding allows a child class to provide a specific implementation...',
'Alex'
);
// Call the overridden method on the Article object
echo $myArticle->getTitleTag();
?>
Expected Output:
<h1>PHP Method Overriding</h1><span>By: Alex</span>
Conclusion
Excellent work! You've now mastered a fundamental technique for creating specialized classes. By overriding methods, you can tailor behavior to fit specific needs while still leveraging the common foundation provided by a parent class.
Key Takeaways:
- Method Overriding is when a child class defines a method with the same name and compatible signature as a method in its parent class.
- You can completely replace a parent's method or, more powerfully, extend it.
- The
parent::methodName()syntax is used to call the parent's implementation from within the child's overridden method. - When overriding, you must follow PHP's visibility and signature compatibility rules.
Preview of the Next Lesson:
So far, our class hierarchies have been built on inheriting implementation from a single parent. But what if you want to guarantee that several unrelated classes all have a certain set of methods? In the next lesson, we will explore interfaces. An interface is like a contract that defines what methods a class must implement, forcing a common behavior without sharing any code. This will shift our focus from "what a class is" to "what a class can do."