PHP Inheritance
Inheritance lets a class (called a child or subclass) reuse the properties and methods of another class (called a parent or superclass), using the extends keyword. This helps avoid duplicating shared logic across related classes.
A child class can override a parent's methods to provide its own specific behavior, and can still call the parent's version of a method using parent::methodName().
class Child extends ParentClass {
function method() {
parent::method();
}
}Extending a class
class Dog extends Animal { } makes Dog inherit all public and protected properties and methods from Animal, while also allowing Dog to add its own.
Overriding methods
A child class can redefine a method with the same name as one in the parent, replacing its behavior. parent::method() calls the original parent implementation if needed.
<?php
class Animal {
function speak() {
return "Some sound";
}
}
class Dog extends Animal {
function speak() {
return "Woof!";
}
}
$d = new Dog();
echo $d->speak();
?>Woof!Dog overrides Animal's speak() method to return its own specific sound.
<?php
class Vehicle {
function info() {
return "A vehicle";
}
}
class Car extends Vehicle {
function info() {
return parent::info() . " that drives on roads";
}
}
echo (new Car())->info();
?>A vehicle that drives on roadsparent::info() calls the original method and extends its result in the child class.
Key points
- extends allows a class to inherit from another class.
- Child classes can override parent methods with their own logic.
- parent::method() calls the parent class's original implementation.
- Inheritance reduces duplicated code between related classes.
