Function overriding in PHP with simple example

Function overriding in PHP with simple example

Function overriding in PHP with simple example



Function overriding in PHP with simple example

What is Overriding

Function overriding is a concept of Object Oriented Programming where we crate function with same name in parent and child class. And PHP calls the function from child class if function present in child class otherwise it looks in parent class. Here is the example





// Main parent class
class Vehicle{
	public $wheel = '4';
	private $color = 'Red';
	public $fuel = 'Petrol';
	public function checkFuelConsumption($fuel,$color){
		if($this->fuel  === 'Petrol'){
			return 25;
		}else{
			return 10;
		} 
	}
}



// Child class
class Bike extends Vehicle{
    // Function overriding using same name function fromparent class
	public function checkFuelConsumption($fuel,$color){
		return 'From Child';
		//return parent::checkFuelConsumption();
		
	}
}

$bike = new Bike();


echo $bike->checkFuelConsumption('Petrol','red');

In the code example you can see we have “”checkFuelConsumption” function in child class. It is also present in parent class. But when we create object of class child class function will be called due to the concept of “Function overriding”. It is important to have same number of argument when calling a function otherwise PHP will generate fatal error.