Inheritance is one of the most powerful features of Object-Oriented Programming. it allows a class to **inherit** properties and methods from another class. This promotes code reusability and helps you create a hierarchical structure in your applications.
In inheritance, we deal with two types of classes:
You use the extends keyword to create a child class that inherits from a parent class.
<?php
class Fruit {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo "The fruit is {$this->name} and the color is {$this->color}.";
}
}
// Strawberry inherits from Fruit
class Strawberry extends Fruit {
public function message() {
echo "Am I a fruit or a berry? ";
}
}
$strawberry = new Strawberry("Strawberry", "red");
$strawberry->message(); // Child method
$strawberry->intro(); // Inherited parent method
?>
Inherited methods can be **overridden** by redefining them in the child class. This is useful when a child class needs to perform the same action but in a different way.
<?php
class Fruit {
public function intro() {
echo "I am a fruit.";
}
}
class Strawberry extends Fruit {
// Overriding the parent method
public function intro() {
echo "I am a strawberry, specifically.";
}
}
$strawberry = new Strawberry();
$strawberry->intro(); // Outputs: I am a strawberry, specifically.
?>
parent::methodName() inside a child class if you want to call the parent's version of the method as well.
The final keyword can be used to prevent class inheritance or to prevent method overriding. If a class is marked as final, it cannot be extended. If a method is marked as final, it cannot be overridden by child classes.
<?php
final class Fruit {
// This class cannot be inherited
}
class Strawberry extends Fruit {
// This will cause a Fatal Error!
}
?>
Vehicle -> Car -> ElectricCar).