Final class in PHP with example

Final class in PHP with example

Final class in PHP with example



Final class in PHP with example

What is Final Keyword

The concept of Final keyword is important as we can restrict the use of class using this keyword. In Object Oriented Programming when you want to make sure that no one can extend the class you made you can add “Final” keyword in from of class. So this class will not be allowed to inherited.





User will get a error that final class cannot be extended.



We can use final keyword with classes and functions only. It cannot be used with variables or constants.





Here see the code example



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


	 final public function checkFuelConsumption(){
		return $this->color;
	}
}



// child class will get error as final keyword added in vehicle class
class Car extends Vehicle{
	// Function overriding won't work due to final keyword
	public function checkFuelConsumption(){
		return $this->fuel;
	}
}

Now if a function is set to final using “Final” keyword it cannot be “overridden” by child class’s function. Hope this gives you the idea how you can limit the use of any class or function using “Final” keyword.