Write a program which shows the use of final keyword in php
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. Show ExampleTo work with the final keyword in PHP, the code is as follows. Here, we have the final method− Live Demo demo(); ?> OutputThis will produce the following output− Derived class function! ExampleLet us now see an example wherein we have a final class − Live Demo demo(); ?> OutputThis 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
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. What is final keyword in PHP with example?Definition and Usage
The final keyword is used to prevent a class from being inherited and to prevent inherited method from being overridden.
What is final method and final class in PHP?Syntax: final Class className. final method: A method is considered a final method if it is prefixed with the final keyword. The final methods are the methods that cannot be overridden. So, these methods can't be overridden in child/subclasses.
What is the use of final keyword on a method?You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final .
How do you declare a final variable in PHP?The final keyword prevents child classes from overriding a method or constant by prefixing the definition with final . If the class itself is being defined final then it cannot be extended. Note: Properties cannot be declared final: only classes, methods, and constants (as of PHP 8.1. 0) may be declared as final.
|