Home >>PHP Object Oriented >PHP Final Class
The final keyword prevents child classes from overriding a method by prefixing the definition with final. It means if we define a method with final then it prevents us to override the method.
<?php class A { final function show($x,$y) { $sum=$x+$y; echo "Sum of given no=".$sum; } } class B extends A { function show($x,$y) { $mult=$x*$y; echo "Multiplication of given no=".$mult; } } $obj= new B(); $obj->show(100,100); ?>
In the above example The class A which is my parent class. In which show method is marked by the final. It means that the show method can not override in any its child class.
To see the error class B define which is extended by A. It means B is the child class of A. In B it is trying to define the final method (show) in class B. Which will produce the fatal error with message Cannot override final method A:: show(). It means we can not define the final method of parent class in its child class.
If the class itself is being defined final then it can not be extended. It means when we define a class with final then it will not allow defining its child class.
<?php final Class A { function show($x,$y) { $sum=$x+$y; echo "Sum of given no=".$sum; } } class B extends A { function show($x,$y) { $mult=$x*$y; echo "Multiplication of given no=".$mult; } } $obj= new B(); $obj->show(100,100); ?>
In the above example class A defines with the final. It means this class can not be extended. When class B defined with extend A ( which means B is the child class of A). But It produces the error with the message "Class B may not inherit from final class (A)". It means that it will not allow creating any child class of A. It means that the final class can not be inherited.