PHP Method Overriding
In this page:
What is Method Overriding?
Method overriding happens when a child class redefines a method that its parent class already has, replacing the parent's behavior with its own version when called on a child object.
Example: What is Method Overriding?
<?php
class Animal {
function speak() {
echo "Some sound";
}
}
class Dog extends Animal {
function speak() {
echo "Bark!";
}
}
$dog = new Dog();
$dog->speak();
?>
Login to try C/C++/Java/PHP code in the editor
The parent Keyword
PHP resolves which version of an overridden method runs based on the actual object's class at runtime, not the type of variable holding it, which is what allows polymorphic code to treat different subclasses uniformly.
Example: The parent Keyword
<?php
class Shape {
function area() {
return 0;
}
}
class Square extends Shape {
function area() {
return 4;
}
}
$shape = new Square();
echo $shape->area();
?>
Login to try C/C++/Java/PHP code in the editor
Overriding Constructors
parent::methodName() inside an overriding method lets you call the parent's original implementation and extend it, rather than replacing it entirely — useful when the child needs to add behavior before or after the inherited logic.
Example: Overriding Constructors
<?php
class Animal {
function speak() {
echo "Generic sound\n";
}
}
class Dog extends Animal {
function speak() {
parent::speak();
echo "Bark!";
}
}
$dog = new Dog();
$dog->speak();
?>
Login to try C/C++/Java/PHP code in the editor
Preventing Overriding with final
An overriding method's signature (parameter types and visibility) generally needs to stay compatible with the parent's, and PHP will raise errors for certain incompatible changes, especially with typed parameters.
Example: Preventing Overriding with final
<?php
class Animal {
function speak(string $sound) {
echo $sound;
}
}
class Dog extends Animal {
function speak(string $sound) {
echo strtoupper($sound);
}
}
$dog = new Dog();
$dog->speak("bark");
?>
Login to try C/C++/Java/PHP code in the editor
Overriding on cookiescursor.com
Overriding is central to polymorphism: a Shape base class might define a generic area() method that Circle and Square each override with their own correct formula, letting calling code just call ->area() without caring which shape it is.
Example: Overriding on cookiescursor.com
<?php
class Shape {
function area() {
return 0;
}
}
class Circle extends Shape {
private $radius;
function __construct($radius) {
$this->radius = $radius;
}
function area() {
return 3.14 * $this->radius * $this->radius;
}
}
class Square extends Shape {
private $side;
function __construct($side) {
$this->side = $side;
}
function area() {
return $this->side * $this->side;
}
}
$shapes = [new Circle(2), new Square(3)];
foreach ($shapes as $shape) {
echo $shape->area() . "\n";
}
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 14 topics to unlock
0/14 topics done
Complete these topics first: