Sobes.tech
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:

  1. Finalizing a class: Applying final to 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
    
  2. Finalizing a method: Applying final to 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.

What does the use of the final keyword prohibit in… - sobes.tech