What is Inheritance in PHP?
Every class has its own properties and methods. Suppose Class A & Class B has its own properties and methods. If Class B want to access Class A properties, here php oops introduce Inheritance concept. Through Php Inheritance many classes and objects relate to one another. The class which properties or methods will used in inheritance is called Base Class And which class is using this method or properties is called derived class.
If we can use more than one inheritance its called multilevel inheritance. please see below image for it.
Example of Inheritance
The Tomato class is inherited from the Vegetable class.
This means that the Tomato class can use the public $name and $color properties as well as the public __construct() and intro() methods from the Fruit class because of inheritance.
The Tomato class also has its own method: message().
<!DOCTYPE html>
<html>
<body>
<?php
class Vegetable {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function intro() {
echo “{$this->name} is fruit and the color is {$this->color}.”;
}
}
// Strawberry is inherited from Fruit
class Tomato extends Vegetable {
public function message() {
echo “Am I a fruit or a Vegetable? “;
}
}
$tomato = new Tomato(“Tomato”, “red”);
$tomato->message();
$tomato->intro();
?>
</body>
</html>