Junior
What is the purpose of the keyword final in PHP?
sobes.tech AI
Answer from AI
The final keyword is used to prevent overriding classes, methods, and constants.
Usage:
-
Classes: If a class is declared as
final, it cannot be inherited.<?php final class Base { // ... } // Fatal error: Class Derived may not inherit from final class Base // class Derived extends Base { // // ... // } -
Methods: If a class method is declared as
final, it cannot be overridden in a subclass.<?php class Base { final public function process() { // ... } } class Derived extends Base { // Fatal error: Cannot override final method Base::process() // public function process() { // // ... // } } -
Constants: Starting from PHP 8.1, class constants can also be declared as
final. This prevents them from being overridden in subclasses.<?php class Base { final public const VERSION = '1.0'; } class Derived extends Base { // Fatal error: Cannot override final constant Base::VERSION // public const VERSION = '1.1'; }
Purpose of final:
- Security: Ensures that key logic or intended behavior of a class/method is not altered in subclasses.
- API Stability: Guarantees that a specific implementation of a method or class will not be modified, which is especially important when developing libraries.
- Performance (slightly): In some cases, it can allow the compiler optimizer to perform more aggressive inline optimizations, knowing that the method will not be overridden.