In this tutorial, you will learn about inheritance in PHP and its uses in PHP for reusing the code to save time and complexity.
Inheritance is used to inherit the definition/characteristics of parent class using extends clause to the child class
Types of Inheritance
- Single Inheritance
- Multilevel Inheritance
- Hierarchical Inheritance
1.Single Inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | <?php class A{ function test(){ echo " This is ClassA Method"; } } class B extends A{ // } $obj=new B(); $obj->test(); ?> Output- This is ClassA Method |
2. Multilevel Inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <?php class A{ function test(){ echo "This is Class A Method"; } } class B extends A{ // } class C extends B{ // } $obj=new C(); $obj->test(); ?> Output - This is Class A Method |
3. Hierarchical Inheritance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php class A{ function test(){ echo "This is ClassA Method"; } } class B extends A{ // } class C extends A{ // } $obj=new B(); $obj=new C(); $obj->test(); ?> Output - This is ClassA Method This is ClassA Method |
Note: PHP does not support Multiple Inheritance.
What are the advantages of Inheritance?
- It reduces the Complexity of the Code
- Reuse of the Code
- Enhance Code redablity