PHP 5 Final Keyword
Final Keyword
PHP 5.1 introduce a keyword which prevents the overriding of class or method named final. You can make any class or method as a final by adding the final in front of class or method.
Need of final keyword
To prevent a class or its method from being inherited, use final keyword
Note : PHP does not allow to declare a variable as final.
PHP 5 Final Class
A class which declare as a final cannot be inherited, let us take example to explain the concept of final class.
Example of Final class
<?php // Final class cannot be Extended final class Computer { public function class_method() { /* Code Here */ } } class Laptop extends Computer { public function class_method() { /* Code Here */ } } ?>
Output
Fatal error: Class Laptop may not inherit from final class (Computer)
If you run this code or script it will throw fatal error as shown above.
PHP 5 Final method or function
A method which declare as a final cannot be overridden, let us take example to explain the concept of final method.
Example final methods
<?php class parent_class { public final function display() { /* Code Here */ } } class child_class extends parent_class { public function display() { /* Code Here */ } } ?>
Output
Fatal error: Cannot override final method parent_class::display()
If you run this code or script it will throw fatal error as shown above.
Why use final keyword?
If you do not want to change the implementation of class or method in child class, declare class or method as a final.