PHP OOPs - Inheritance

What is Inheritance in php?

When the child class can inherit all the public and protected properties and methods from the parent class, it is called Inheritance.

Inheritance can be implemented by using 'extends' keyword.

We can access all parent class properties and methods using object of child class.

Mulltiple Inheritance can not be supported by PHP. child class can only extend one parent class.

A protected properties or methods can be accessed only inside child class.

PHP Syntax:

class Child extends Parent

Child class is also called as sub class or Derived class. Parent class is also called as super class or base class.

PHP Example :

<?php
//code by aryatechno!
class Superclass{
   public function publicmethod(){
      echo "It is public method of super class\n" ;
   }
   protected function protectedmethod(){
      echo "It is protected method of super class\n" ;
   }
   private function privatemethod(){
      echo "It is private method of super class\n" ;
   }
}
class Subclass extends Superclass{
   public function submethod(){
      $this->protectedmethod();
      //$this->privatemethod(); //Generates PHP Fatal error:  Uncaught Error: Call to private method Superclass::privatemethod() from scope Subclass.
   }
}
$obj=new Subclass();
$obj->publicmethod();
$obj->submethod();
?>

Output:

It is public method of super class
It is protected method of super class

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

76460