Multiple And Hybrid Inheritance: PHP OOP


Video tutorial to illustrate Inheritance mechanism in Object Oriented PHP.

Inheritance is a mechanism where objects of one class acquires the properties of objects of another class.

PHP supports only single inheritance.
i.e., a class should inherit from only one parent class / base class. If it inherits from more than one base class, then it’s not a valid inheritance in PHP.

Thus, multiple inheritance and hybrid inheritance is not supported in Object Oriented PHP.

Single Inheritance
class B inherits from class A

single-inheritance-classA-to-classB

class C inherits from class B which in turn inherits from class A

single-inheritance-classA-to-classB-to-classC

class B and class C inherits from class A

single-inheritance-classA-to-classB-and-classC

Invalid Inheritance in PHP
Multiple Inheritance
class A inherits from two base/parent classes B and C

multiple-inheritance-classB-classC-to-classA

Hybrid Inheritance
class B and C inherits from a single base/parent class, i.e., class A
again, class D inherits from class B and class C

hybrid-inheritance

Single Inheritance: class B and class C inherits from class A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
< ?php
class A
{
function display()
{
echo "Apple, Google, Oracle, Microsoft";
}
}
 
class B extends A
{
 
}
 
class C extends A
{
 
}
 
$obj = new C(); 
//$obj = new A(); 
//$obj = new B(); 
$obj->display();
?>

This should output
Apple, Google, Oracle, Microsoft

Multiple And Hybrid Inheritance: PHP OOP


[youtube https://www.youtube.com/watch?v=vEubH2KVgYk]

YouTube Link: https://www.youtube.com/watch?v=vEubH2KVgYk [Watch the Video In Full Screen.]



Try yourselves:
If you try to extend class A and class B to class C, it’ll through fatal error.

Related Read:
Single Inheritance: PHP OOP

Note:
So, technically you can’t extend/inherit from more than 1 base/parent class.
To overcome this situation, we can make use of Interfaces.
Interfaces in PHP works similar to that of Java. We’ll teach interfaces in another video tutorial, so stay subscribed.

Leave a Reply

Your email address will not be published. Required fields are marked *