Php Inheritance

What is Php Inheritance?

inheritance is a mechanism, we can get all property and method of one class into another class.We can access all property and method through extends keyword.

Inheritance represents the IS-A relationship, also known as parent-child relationship.
What is IS-A relationship?
Is a Relationship-page0001

In this image, Narendra Modi is a Prime Minister, Narendra Modi is a Son and Narendra Modi is a politician. so this is called Is a relationship.

Why use Inheritance?
(i) For Code Reusability.
(ii) For Method Overriding.

Note:-
(i) The subclass inherits all of the public and protected methods from the parent class.
(ii) If a class extends another, then the parent class must be declared before the child class structure.

Syntax:-


<?php 
class childclass(or subclass) extends parentclass(or superclass)
{
}
?>

Example of Inheritance

In this example, generalManager class inherit the property and method of Empoyees class, officeTiming() Method of generalManager class, override the method of Empoyees class.


<?php 
class Empoyees {
	public function officeTiming(){
	echo 'Employee Office Timing is 10am to 7pm';
	}
}

class generalManager extends Empoyees {
    public function officeTiming(){
	echo 'General Manager Office Timing is 10am to 5pm';
	}

}

$gm_obj = new generalManager;
$gm_obj -> officeTiming();
?>
Output:- General Manager Office Timing is 10am to 5pm

Type of Inheritance

There are mainly 3 types of Inheritance in Php.
(i) Single Inheritance
(ii) Multilevel Inheritance
(iii) Hierarchical Inheritance

simple-Inheritance

two other inheritance used through Interface.
(iv) Multiple Inheritance
(v) Hybrid Inheritance

multiple-Inheritance

Why Multiple inheritance is not support Php language

Without Interface, Multiple inheritance is not support Php language.

Without Interface Multiple inheritance program
notsupport_multiple_inheritance

Output:- Compile time error, syntax error, unexpected ‘,’, expecting ‘{‘

Multiple inheritance By Interface
This section is explained in the Interface section.