Friday, February 21, 2014

PHP oops Multilevel Inheritance Example





class GrandFather
{
	public function gfAge()
	{
		return  ' age is 80';
	}

}

class Father extends GrandFather
{
		
	public function fAge()
	{
		return  ' age is 50';
	}

}

class Son extends Father
{
	public function sAge()
	{
		return  'age is 20';
	}

     public function myHistory()
     {
	 echo "my grand father ".parent::gfAge();
	 echo "my father ".parent::fAge();
       echo "my ".$this->sAge();
     }
	
}


$son = new Son();

$son->myHistory();

// output is

//my grand father age is 80
//my father age is 50
//my age is 20

Above code shows simple example for multi level inheritance,

class GrandFather is a base class , extended by Father class and this is extended by

Son class

myHistory function in Son class access Father class and GrandFather class functions

here the class hieararchy is,


GrandFather
    |
    | 
  Father
    |
    |
   Son 

 

4 comments: