PHP MySQL tutorial

Inheritance in Object Oriented PHP

Inheritance in object oriented PHP is similar to inheritance in real world. A child inherit some of the characteristics of its parents while develop some of his own. In the same way in PHP, a class that inherits another class inherits all the member variables and functions of its parent class and have some of its own as well. Before delving into an example let us first define some terms.

A parent or base class

A parent class or a base class is class from which other classes inherit. A base class usually contains characteristics that are common in its child classes. An Item class defined in the last article can be considered as base class

A child or derived class

A child class or derived class is a class that derives from the parent or base class. Child class usually has properties that are intrinsic to it. For example, a class ElectronicsItem can be child class of the base Item class. Let’s have a look at the following example to see how inheritance is implemented in PHP.

itemname = $name;
           $this->itemprice = $price;   
       /* Function to get name of item */
      function getName(){
         echo $this->itemname ."
"; } } // Child class extending electronics items class ElectornicsItem extends Item { var $voltage; function ElectornicsItem($name, $price, $vol) { Item :: Item($name, $price); $this->voltage = $vol; } function getVoltage() { echo $this->voltage ."
"; } } $elecItem = new ElectornicsItem("Laptop", 35000, 220); $elecItem -> getName(); $elecItem -> getPrice(); $elecItem -> getVoltage(); ?>

Download the code
Run the code

In the above code a child class named ElectronicsItem has been created which inherits the Item class. The child class contains one member variable voltage and function getVoltage which returns this voltage. Notice in this example another way of creating constructor has been used. You can create a function with the same name as the name of the class and it will work as constructor of the class. The child class constructor takes three parameters, two of those parameters are passed to parent class constructor using “::” symbol which sends call to parent class constructor.

Now, if you create object of the ElectronicsItem class and print, name, price and voltage you will see all of them printed despite the fact that ElectronicItem class does’t contain name and price. They have become part of ElectronicsItem class because this class is inheriting Item class which actually contain these variables.

<<< Parameterized Constructors in PHPAbstract Class in PHP >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .