Inheritance

Getting Started with PHP
Getting Started with PHP : Home
Introduction
Installation
Hello World
Data Types in PHP
Variables in PHP
Operators in PHP
Decision Making in PHP
Iterations in PHP
Functions in PHP
Arrays in PHP
Strings in PHP
Object Oriented PHP
Classes and Objects
Constructors
Inheritance
Object Interfaces
Static and Final
Advanced Features in PHP
GET and POST
Session in PHP
Cookies in PHP
Server Variables

Inheritance
We can reuse the all the public, protected properties and methods in a new class using inheritance.
In PHP, we use extends. The class which is to be inherited is parent class and the new class is called child class. We can also override methods of the parent class in the child class.
The parent class remains uneffected with inheritance.

<?php
 class parentClass{
 	public $name;
 	public $id;
 	function __construct($name,$id){
 		$this->name = $name;
 		$this->id = $id;
 	}
 	function showdetails(){
 		echo $this->name."\n".$this->id."<br>";
 	}
 }

 class childClass extends parentClass{
 	public $type = "inherited class";
 	// Overriding parent class function
 	
 	function showdetails(){
 		echo $this->name."\n".$this->id."\n".$this->type;	
 	}
 }

 $obj_par = new parentClass("parent",10);
 $obj_ch = new childClass("child",20);

 $obj_par->showdetails(); // call method of parent class
 $obj_ch->showdetails();  // call method of child class

?>


Output
parent 10
child 20 inherited class

Class Abstraction
Abstract Class
If a class is delcared as Abstract class, it can't be instantiated i.e. you can't create object for that class.
You might be wondering that what's the purpose of that class. We make use of Abstract class using inheritance i.e. used as parent class.
Any class having a abstract method must be declared as abstract class.

Abstract Method
A abstract method has only declaration and no implimentation.
All the abstract methods must be implemented while extending (inheriting from) a Abstract class in the child class.
Abstract classes and methods are declared using keyword abstract.

<?php
 abstract class item{
 	protected $name;
 	function __construct($name){
 		$this->name = $name;
 	}
 	abstract function showIteam(); // abstract method
 								// only declaration
 }
 class realIteam extends item{ //implementing abstract class
 	function showIteam(){ // implementing abstract method
 		echo $this->name;
 	}
 }

 $object = new realIteam("dummy");
 $object->showIteam();
?>


Output
dummy

Login to Track Your Progress