Inheritance is an important principle of object oriented programming methodology. Using this principle, relations between two classes can be defined. PHP supports inheritance in its object model. PHP uses extended keywords to establish relationships between two classes.

class B extends A

where A is the base class (also called parent class) and B is called a subclass or child class. Child class inherits public and protected methods of parent class. Child class may redefine or override any of inherited methods. If not, inherited methods will retain their functionality as defined in parent class, when used with objects of child class.

Definition of parent class must precede child class definition. In this case, the definition of A class should appear before the definition of class B in the script.

<?php

class A{

   //properties, constants and methods of class A

}

class B extends A{

   //public and protected methods inherited

}

?>

Example

<?php

class parentclass{

   public function publicmethod(){

      echo “This is public method of parent class

” ;

   }

   protected function protectedmethod(){

      echo “This is protected method of parent class

” ;

   }

   private function privatemethod(){

      echo “This is private method of parent class

” ;

   }

}

class childclass extends parentclass{

   public function childmethod(){

      $this->protectedmethod();

      //$this->privatemethod(); //this will produce error

   }

}

$obj=new childclass();

$obj->publicmethod();

$obj->childmethod();

?>

Output

Result. −

This is public method of parent class

This is protected method of parent class

PHP Fatal error: Uncaught Error: Call to private method parentclass::privatemethod() from context ‘childcl