Inherit the class is tremendous flexibility for overwriting a class or method which the call the class method using the instance of the class and provide completely different results.But sometimes, You might need a class or methods which remain unchanged. To achieve such functionality, you need to use the final keyword.
PHP 5 supports a final keyword.The final keyword is used to define classes and methods.If the parent class method is declared as final, the subclass can not override this method. if a class is declared final, can not be inherited.
Today I am going to explain one of the features in PHP5 and it is a Final keyword. As I am aware of java so I know final keywords in java also.
What is Final?
The final keyword is used at class and method level, not useful at properties level. A class that can’t have subclass is a Final class. A method that can’t be overridden is the final method.The main purpose behind final keyword is to protect class or method to extend because of some security reasons.
Declaring a class as final means to prevent any unwanted extensions to the class, therefore, final can’t be used as inheritance so we can say final class is like a constant.
NOTE: If we use any class as ABSTRACT then its not a FINAL.
SYNTAX
Final is used with keyword Final.The following defines a final Keyword syntax:
1 2 3 4 5 6 7 | Final class Class_name{ ....... ....... } Final method method_name() |
Examples
Let’s see examples for Final Class and Final method
FINAL CLASS:
The following code does not work:
1 2 3 4 5 6 7 8 9 10 11 12 13 | final class A{ // Final class can't be extended { echo "This is final class"; } } class B extends A{ function meth(){ } } //Fatal error: Non-abstract method B::meth() |
Here, It’s illegal for class B to inherit class A because A is declared as Final.The result of the program is the Fatal error: Class B can not inherit from the Final class, trying to inherit class B when the class A is final so the system leads to error. Similarly, if a final keyword is used for the class method, the subclass can not override it, the method is final.
What is Final Method?
Next, we move on to an example of final methods and below code shows that how final method works
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | class C{ final function fmeth() // Final method can't be override { echo "This is final class"; } } class D extends C{ function fmeth(){ } } //Fatal error: Cannot override final method C::fmeth() |
Here, It’s illegal for class B to inherit class A because A is declared as Final
NOTE: All classes are Base class until its not declared as final.
I hope you have got the idea about final keywords in PHP by this post. Also, read how to create Pagination in CodeIgniter.Do let me know if you have used final methods or class for practical approach in your application. Don’t forget to share with your friends on Facebook & Google plus.
Comments (4)