Skip to main content

In PHP, the `final` keyword is used to restrict the inheritance and overriding of methods and classes. Here's what it does in different contexts:

  1. Final methods: When you declare a method as `final` within a class, it means that the method cannot be overridden by any subclass that extends that class. It effectively prevents the subclass from redefining the method implementation.
    <?php
    
    class ParentClass {
        final public function someMethod() {
            // Method implementation
        }
    }
    
    class ChildClass extends ParentClass {
        // This will cause an error since overriding final method is not allowed
        public function someMethod() {
            // New method implementation
        }
    }
    In the above example, the `someMethod()` in the `ParentClass` is declared as `final`, which means that the `ChildClass` cannot override it. If the `ChildClass` tries to override the `someMethod()` method, it will result in an error.
  2. Final classes: When you declare a class as `final`, it means that the class cannot be extended by any other class. In other words, it prevents inheritance from that class.
    <?php
    
    final class FinalClass {
        // Class implementation
    }
    
    class ChildClass extends FinalClass {
        // This will cause an error since extending a final class is not allowed
    }
    In the above example, the `FinalClass` is declared as `final`, which means that no other class can extend it. If a class tries to extend the `FinalClass`, it will result in an error. The `final` keyword is useful when you want to ensure that a method or a class should not be modified or extended, providing a level of control over the inheritance and method overriding in your PHP code.

The final keyword is also relevant in other OO programming languages like Java, C# and C++. 

Tags

x

Work

Therefore logo
80 Atlantic Ave, Toronto, ON Canada
Email: hello@therefore.ca
Call us: +1 4166405376
Linkedin

Let us know how we can help!