Inheritance in PHP is a feature of Object-Oriented Programming (OOP) that allows a class to inherit the properties and methods of another class.
It is a way of reusing code, and makes it easier to maintain and update the code.
Inheritance is a very important concept in OOP, and it is used to extend the functionality of existing classes.
Sample Code
<?php
class Car {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function answer() {
echo "The car is {$this->name} and the color is {$this->color}.";
}
}
// Volvo is inherited from Car
class Volvo extends Car {
public function question() {
echo "Am I a car or a van? ";
}
}
$volvo = new Volvo("Volvo", "red");
$volvo ->question();
echo “<br>”;
$volvo ->answer();
?>
Output
Am I a car or a van?
The car is Volvo and the color is red.
PHP - Overriding Inherited Methods
Inherited methods can be overridden by redefining the methods (use the same name) in the child class.
Sample Code
<?php
class Car {
public $name;
public $color;
public function __construct($name, $color) {
$this->name = $name;
$this->color = $color;
}
public function message() {
echo "The car is {$this->name} and the color is {$this->color}.";
}
}
class Volvo extends Car {
public $type;
public function __construct($name, $color, $type) {
$this->name = $name;
$this->color = $color;
$this->type = $type;
}
public function message() {
echo "The car is {$this->name}, the color is {$this->color}, and the type is {$this->type}.";
}
}
$volvo = new Volvo("Volvo", "black", "sedan");
$volvo->message();
?>
Output
The car is Volvo, the color is black, and the type is sedan.
Related Searches to PHP OOPs Inheritance - PHP Inheritance
php oop inheritanceobject inheritancephp oops inheritancephp object inheritanceinheritance in phpphp inheritancephp inheritance and its typesmultiple inheritance in phptypes of inheritance in phpphp inheritance constructorphp inheritance typesmultilevel inheritance in php