PHP - Blocking Inheritance and Overrides with Final Classes and Methods

Introduction

To lock down a class so that it can't be inherited from.

To lock down one or more methods inside a class so that they can't be overridden in a child class.

By doing this, you know that your class or methods within your class will always behave in exactly the same way.

You can add the keyword final before a class or method definition to lock down that class or method.

<?php
        final class HandsOffThisClass {
          public $someProperty = 123;
          public function someMethod() {
            echo "A method";
          }
         }

        // Generates an error:
        //"Class ChildClass may not inherit from final class (HandsOffThisClass)"
        class ChildClass extends HandsOffThisClass {
        }
?>

Similarly, here's how you make a final method:

<?php
        class ParentClass {
          public $someProperty = 123;
          public final function handsOffThisMethod() {
            echo "A method";
          }
         }

         // Generates an error:
         //"Cannot override final method ParentClass::handsOffThisMethod()"

         class ChildClass extends ParentClass {
          public function handsOffThisMethod() {
            echo "Trying to override the method";
          }
         }
?>

Related Topic