Overriding in PHP Object-Oriented Programming allows child classes to redefine properties and methods inherited from parent classes. This enables flexible behavior and supports polymorphism.
parent:: can access original behaviorWhen a child class defines a method or property with the same name as its parent, PHP uses the child version during runtime. This makes behavior customizable without changing base classes.
// Parent class definition
<?php
class ParentClass {
public $name = "Parent";
public function greet() {
echo "Hello from Parent!";
}
}
// Child class overriding property and method
class ChildClass extends ParentClass {
public $name = "Child";
public function greet() {
echo "Hello from Child!";
}
}
// Creating object of child class
$child = new ChildClass();
echo $child->name;
$child->greet();
?>
The output displays Child as the property value and prints the child class greeting message. PHP prioritizes the overridden definitions in the child class.
Imagine a blueprint system where the base design is reused, but details are customized per requirement — overriding works the same way in OOP.
parent::method() when extending logicVehicle class and override start() in Carparent:: inside an overridden method