The final keyword is used in PHP for methods and classes. The final for methods prevent method overriding, whereas for classes with final prevent Inheritance.
Example
To work with the final keyword in PHP, the code is as follows. Here, we have the final method−
Live Demo
Output
This will produce the following output−
Derived class function!
Example
Let us now see an example wherein we have a final class −
Live Demo
Output
This will produce the following output i.e. an error since we tried creating a derived class from a final base class−
PHP Fatal error: Class Derived may not inherit from final class [Base] in /home/cg/root/6985034/main.php on line 19
Updated on 02-Jan-2020 06:34:50
- Related Questions & Answers
- PHP final Keyword
- Final keyword in C#
- final keyword in Java
- final keyword in Dart Programming
- Explain final class and final method in PHP.
- Using final keyword to Prevent Overriding in Java
- PHP namespace keyword and __NAMESPACE__ constant
- Can a final keyword alone be used to define a constant in Java?
- What is "namespace" keyword in PHP?
- final variables in Java
- Final variables in C#
- Blank final in Java
- Final Arrays in Java
- Final variable in Java
- Final class in Java
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Final keyword in PHP is used in different context. The final keyword is used only for methods and
classes.
Final methods: When a method is declared as final then overriding on that method can not be performed. Methods are declared as final due to some design reasons. Method should not be overridden due to security or any other reasons.
Example:
Output:
Base class final printdata function Derived class non final function
Final Classes: A class declared as final can not be extended in future. Classes are declared as final due to some design level issue. Creator of class declare that class as final if he want that class should not be inherited due to some security or other reasons. A final class can contain final as well as non final methods. But there is no use of final methods in class when class is itself declared as final because inheritance is not possible.
Example:
Output:
final base class final method non final method of final base class
Note: Unlike Java final keyword in PHP can only be used for methods and classes not for variables.