0
0
PHPprogramming~5 mins

Method overriding in PHP

Choose your learning style9 modes available
Introduction

Method overriding lets a child class change how a method from its parent works. This helps customize behavior without changing the parent.

You want a child class to do something different when calling a method that exists in the parent.
You have a general method in a parent class but need specific versions in child classes.
You want to reuse code but still change small parts of how it works in different classes.
Syntax
PHP
<?php
class ParentClass {
    public function methodName() {
        // parent method code
    }
}

class ChildClass extends ParentClass {
    public function methodName() {
        // child method code overrides parent
    }
}
?>
The child method must have the same name as the parent method to override it.
The child method can call the parent method using parent::methodName() if needed.
Examples
The Dog class changes the sound method to print "Bark" instead of "Some sound".
PHP
<?php
class Animal {
    public function sound() {
        echo "Some sound";
    }
}

class Dog extends Animal {
    public function sound() {
        echo "Bark";
    }
}
?>
The Car class overrides start but also calls the parent method first.
PHP
<?php
class Vehicle {
    public function start() {
        echo "Vehicle started";
    }
}

class Car extends Vehicle {
    public function start() {
        parent::start();
        echo " and car engine is running";
    }
}
?>
Sample Program

This program shows how ColorPrinter changes the message printed by overriding printMessage from Printer.

PHP
<?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();
?>
OutputSuccess
Important Notes

Method overriding only works with inheritance (child and parent classes).

Access modifiers like public or protected should be compatible between parent and child methods.

Summary

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().