What Does the Final Keyword Do in PHP?

Declaring a class or method as final in PHP is a fundamental object-oriented programming technique used to restrict inheritance and method overriding. This article explains the mechanics of the final keyword, demonstrates how it affects classes and methods with clear code examples, and outlines when and why you should use it in your software development workflow.

Final Classes

When you prepend a class definition with the final keyword, you prevent any other class from extending it. This means the final class cannot have any child classes (subclasses).

Example of a Final Class

final class Configuration {
    public $theme = 'dark';
}

// This will trigger a Fatal Error:
// Class AdminConfiguration may not inherit from final class (Configuration)
class AdminConfiguration extends Configuration {
    // ...
}

Using a final class is highly effective when you want to freeze the functionality of a class and ensure that its behavior is not modified or specialized through inheritance.

Final Methods

If you do not want to block inheritance for an entire class, but you want to protect specific behavior from being altered, you can declare individual methods as final. A final method can be inherited by a child class, but it cannot be overridden or redefined within that child class.

Example of a Final Method

class User {
    protected $id;

    // This method cannot be overridden by subclasses
    final public function getId() {
        return $this->id;
    }
}

class PremiumUser extends User {
    // This will trigger a Fatal Error:
    // Cannot override final method User::getId()
    public function getId() {
        return $this->id . '-premium';
    }
}

In this scenario, PremiumUser can still inherit other properties and non-final methods from User, but the core identity logic inside getId() remains securely locked.

Why Use the Final Keyword?

Declaring classes and methods as final provides several architectural and practical benefits: