Introduction
Method overriding lets a child class change how a method from its parent works. This helps customize behavior without changing the parent.
Method overriding lets a child class change how a method from its parent works. This helps customize behavior without changing the parent.
<?php class ParentClass { public function methodName() { // parent method code } } class ChildClass extends ParentClass { public function methodName() { // child method code overrides parent } } ?>
parent::methodName() if needed.Dog class changes the sound method to print "Bark" instead of "Some sound".<?php class Animal { public function sound() { echo "Some sound"; } } class Dog extends Animal { public function sound() { echo "Bark"; } } ?>
Car class overrides start but also calls the parent method first.<?php class Vehicle { public function start() { echo "Vehicle started"; } } class Car extends Vehicle { public function start() { parent::start(); echo " and car engine is running"; } } ?>
This program shows how ColorPrinter changes the message printed by overriding printMessage from Printer.
<?php class Printer { public function printMessage() { echo "Printing from Printer"; } } class ColorPrinter extends Printer { public function printMessage() { echo "Printing in color"; } } $printer = new Printer(); $printer->printMessage(); echo "\n"; $colorPrinter = new ColorPrinter(); $colorPrinter->printMessage(); ?>
Method overriding only works with inheritance (child and parent classes).
Access modifiers like public or protected should be compatible between parent and child methods.
Method overriding lets child classes change parent methods.
Use the same method name in child to override.
You can still call the parent method inside the child method with parent::methodName().
greet in a child class in PHP?function greet() correctly without extra keywords.class ParentClass {
function sayHello() {
echo "Hello from Parent";
}
}
class ChildClass extends ParentClass {
function sayHello() {
echo "Hello from Child";
}
}
$obj = new ChildClass();
$obj->sayHello();sayHello() which overrides ParentClass method.sayHello(), printing "Hello from Child".class Base {
function show() {
echo "Base";
}
}
class Derived extends Base {
function show() {
parent.show();
echo " Derived";
}
}
$obj = new Derived();
$obj->show();parent.show() which is invalid syntax in PHP.parent::show() to call the parent's method inside child.class Animal {
function sound() {
echo "Some sound";
}
}
class Dog extends Animal {
function sound() {
parent::sound();
echo " and Bark";
}
}
class Puppy extends Dog {
function sound() {
echo "Yip";
}
}
$pet = new Puppy();
$pet->sound();sound() and only echoes "Yip" without calling parent.parent::sound(), Dog and Animal methods are not executed.Pass the test and this pattern moves unknown