Middle
What does the use of the final keyword prohibit in PHP?
sobes.tech AI
Answer from AI
The keyword final in the context of PHP is used to prevent inheritance and overriding:
-
Finalizing a class: Applying
finalto a class prohibits creating subclasses that inherit from it.<?php final class BaseClass { // ... } // class DerivedClass extends BaseClass {} // Fatal error: Class DerivedClass cannot inherit from final class BaseClass -
Finalizing a method: Applying
finalto a method within a class prohibits overriding that method in subclasses.<?php class ParentClass { final public function cannotBeOverridden() { // ... } public function canBeOverridden() { // ... } } class ChildClass extends ParentClass { // public function cannotBeOverridden() {} // Fatal error: Cannot override final method ParentClass::cannotBeOverridden() public function canBeOverridden() { // Overriding is allowed } }
final cannot be applied to class properties.