In this tutorial we are going to learn PHP Final Keyword with Example. If you are new to Object Oriented Programming then please learn it as PHP final keyword used with Classes and methods.
Use of PHP Final Keyword :
- PHP Final Classes prevent inheritance
- Final Methods prevent Method Overriding
Final Class Example :
If we declare a class as final class then subclass can’t its extend parent class.
<?php final Class Parent { public function calculate($x,$y) { $multi=$x*$y; echo "Multiplication of given no =".$multi; } } class Child extends Parent { function calculate($x,$y) { $sum=$x+$y; echo "Sum of given no =".$sum; } } $obj= new Child(); $obj->calculate(10,5); ?>
If run above code then you will get error.
Final Method Example :
If we declared a method as final method in parent class then its subclass can’t override parent class method.
<?php class Parent { final function calculate($x,$y) { $multi = $a*$b; echo "Multiplication = ".$multi; } } class Child extends Parent { public function calculate($a,$b) { $sum = $x+$y; echo "Sum = ".$sum; } } $obj= new Child(); $obj->calculate(10,5); ?>
If run above code then you will get error.