Inheritance in PHP

Inheritance in PHP : inherit or use all properties and methods of one class(Parent or Base Class) to another class(child class).

Inheritance is the process of driving a new class from existing class,inherit the all features(Methods and Properties) of base class(Parent Class) in child class with extra features

Example - Single Inheritance

class PHP
{
//PHP is parent class
}
class Mysql extends PHP
{
//Mysql is child class
}

Summery of Inheritance

  • inherit only protected and public(properties and methods()) from parent class
  • inherit parent class using keyword extends
  • Use for re-usability of code.

Multilevel Inheritance in PHP

class A
{
//code
}
class B extends A
{
//code
}
class C extends B
{
//code
} 

In above example of multilevel inheritance class(B) is inherit class(A) property and methods.child class(C) is inherit class(B) property and method.
In child class(C) have class(B) and class(C) features.

Multiple inheritance in PHP

class php
{
//code
}
class mysql
{
//code
}
class html extends php mysql
{
//code
} 
//It does not support multiple inheritance.

Example 1 - Single Inheritance

class PHP
{
	function test()
	{
	 echo 'a';
	}
}
class Mysql extends PHP
{
	function test()
	{
	 echo 'b';
	}
}

$php_obj = new PHP();
$php_obj->test(); 
//output: a 

$mysql_obj = new Mysql();
$mysql_obj->test(); 
//output: b // it's override test method 

Interview Questions in PHP Inhertence

class A{
	function xyz()
	{
		echo 'Parent ';
	}
	function xyzW()
	{
		$this->xyz();
	}
}
class B extends A
{
	function xyz()
	{
		echo 'childClass';
	}
}
$a = new A();
$a->xyz();
$b=new B();
$b->xyzW();
//output :: Parent childClass