OOPS in PHP 5 Tutorial - Exploring Inheritance

This tutorial will guide you through one of the main feature of Object Oriented Programing which is called Inheritance. Basically Inheritance is a mechanism where a new class is derived from the existing base class. The derived class shares/inherit the functionality of the base class. To extend the class behavior PHP5 have introduced a new keyword called “extends“.





While performing Inheritance operation Access Specifiers specify the level of access that the outside world (other objects and functions) have on the data members / member functions of the class. During Inheritance operation the derived class can access the parent class attributes having protected/public access specifier. To access private data of parent class from derived class you will have to call public/protected method of the parent class which will access the private variable and return the data to the derived class. In PHP5 only single inheritance is allowed. i.e. You can inherit only one class.

Example 1 - Parent Keyword in Inheritance Error

< ?
class parent     //Generates an error
{
    private $firstname;
    private $lastname;
}
 
class children extends parent
{
    function __construct()
    {
       echo $this->firstname;
       echo $this->lastname;
    }
}
$a = new children();
?>

Output: Generate error in PHP5 as parent is keyword in PHP5.
Explanation: Parent is the Keyword in PHP5 and it cannot be used in PHP5 for declaring classname.

Example 2 - Basic Inheritance Call

< ?
class parent1
{
    protected $firstname = 11;
    protected $lastname = 23;
}
 
class children extends parent1
{
   function __construct()
   {
       echo $this->firstname;
       echo $this->lastname;
   }
}
$a = new children();
?>

Output: 1123
Explanation: Parent1 class have extending its functionality to the children class. Now the children class can access the $firstname and $lastname attributes.

Example 3 - Accessing Private Data Member through Inheritance

< ?
class parent1
{
      private $firstname = "hitesh";
      protected $lastname = 23;
 
      protected function getData()
      {
             return $this->firstname;
      }
}
 
class children extends parent1
{
      function __construct()
      {
         echo $this->getData();
      }
}
 
$a = new children();
?>

Output: hitesh

Similar Posts

Custom Search

Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.

Comments

hi there…

thanx…

hi…

Agree…

good work

Really very useful. Thanx for your work done here

Leave a comment

(required)

(required)