Inheritance and function overriding are the necessary component of almost every programming language. Here when we talk about Inheritance then we can say is an important concept in all programming languages to increase code reusability. It is also use in PHP. It is use when we need to use the functionality of one class into another class to generate a reusable code. The classes have parent child relationship in inheritance. The child class inherit/adopt all the properties of his parent class. By creating the object of child class we can access all the function and variables of parent class too.Before going towards Inheritance and function overriding you must click and read the previous article given below: 

              Also read:    OOP in PHP Part 2, What is constructor.?

<?php

class Laptop{

        public $model;

        public $volume;

function volumeUp(){

        $this->volume++;

}

function volumeDown(){

        $this->volume–;

}

function __construct(){

        $this->model=’proinertech’;

        $this->volume='<br>’. 1;

      }

}

class Touchlapi extends Laptop{

        public $timer;

}

$touch = new Touchlapi();

echo $touch->model;

echo $touch->volume;

?>

Here is the out put:

inheritance and function overriding in php

From above you have notice we use extend keyword. The purpose of this keyword is to derive a child class from above parent class Laptop. The child class is Touchlapi and it has all the attributes of its parent class “Lapi”. Moving further in this article on Inheritance and function overriding now we will discuss about function overriding and variable overriding.

Function and Variable overriding

We can also create new functions and variables in child class which will override the varibles and functions of parent class.

 For exaple when we create a new construc function in child class it will override the construct class in parent class. The child class call the function of its own istead of calling to his parent class. Same case is in variable, we can override the variables too.

<?php

class Laptop{

        public $model;

        public $volume;

function volumeUp(){

        $this->volume++;

}

function volumeDown(){

        $this->volume–;

}

function __construct(){

        $this->model=’proinertech’;

        $this->volume='<br>’. 1;

     }

}

class Touchlapi extends Laptop{

        public $model=’touchlapi’;

        public $timer;

        function __construct($m,$v){

                $this->model=$m;

                $this->volume=$v;

        }

}

$touch = new Touchlapi(‘sony’,1);

echo $touch->model;

?>

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.