When the properties and the methods of the parent class are accessed by the child class, we call the concept has an inheritance. The child class can inherit the parent method and give its own method implementation, this property is called the overridden method. When the same method of the parent class is inherited we call it as an inherited method. Now let us see types of inheritance supported in Object Oriented Programming and corresponding Php inheritance examples.
In Single Level Inheritance, the Parent class methods will be extended by the child class. All the methods can be inherited.
For implementing the single inheritance concept in PHP, we require two classes one as a parent and the other as a child. Let us have two such classes named A and B, respectively as shown below.
Example for Single Level Inheritance
<?php
class A {
public function getItem($string) {
echo "Hello :" . $string;
}
public function getPHP() {
echo "I am from valuebound" . PHP_EOL;
}
}
class B extends A {
public function getItem($string) {
echo "Hi:" . $string . PHP_EOL;
}
public function getPHP() {
echo "I am from ABC";
}
}
$a = new A();
$b = new B();
$a->getItem("Karan");
$a->getPHP();
$b->getItem("Shivani");
$b->getPHP();
?>
Hello: Karan
I am from valuebound
Hello: Shivani
I am from ABC
In Multi level Inheritance, the parent class method will be inherited by child class and again subclass will inherit the child class method.
<?php
class A {
public function getMyage() {
return "age is 90";
}
}
class B extends A {
public function getMysonage() {
return "age is 60";
}
}
class C extends B {
public function getMygrandsonage() {
return "age is 30";
}
public function getmyHistory() {
echo "Class A " .$this->getMyage();
echo "Class B ".$this-> getMysonage();
echo "Class C " . $this->getMygrandsonage();
}
}
$obj = new C();
$obj->getmyHistory();
?>
Class A is 90
Class B is 60
Class C 30
© 2025 Easy To Learning. All Rights Reserved | Design by Easy To Learning