INHERITANCE IN PHP 7

INHERITANCE IN PHP 7

INHERITANCE IN PHP 7



INHERITANCE IN PHP 7

What is Inheritance

In Object Oriented Programming inheritance is a concept of extending a class. So if you have a base class let’s say “Vehicle Class”. This class might have functions those can be applied to all vehicles such as wheels, colour, fuel etc. So if you create a child class named “Car class”. Then car class can extend Vehicle class to access these functions. But Car class might have functions like “doors” as not all vehicles have doors for example bike. So “door” is function that declares in child class only.





Visibility In Inheritance

We can access public and protected properties in child class but we cannot access private properties as private properties and function can be used in class where they are defined.



Example of Inheritance

Let’s see some code to understand Inheritance.





//Main class

class Vehicle{
	public $wheel = '4';
    //private variable
	private $color = 'Red';
	public $fuel = 'Petrol';

    //function calling private variable
	public function checkFuelConsumption(){
		return $this->color;
	}
}


//Child class extending parent class

class Car extends Vehicle{
    // function calling parent class function
	public function display(){
		return $this->checkFuelConsumption();
	} 
}

Here you can see “Car Class” calling function checkFuelConsumption from parent class because “Car Class” extending “Vehicle Class” so have access to all “Public and Protected methods and variables”.