Object-oriented programming in PHP gives developers powerful inheritance features. However, not every class is designed to be extended. That’s where the final keyword comes in.
A final class explicitly tells PHP that this class cannot be inherited. It protects the class from being extended and helps preserve its intended behavior.
When you declare a class as final, PHP prevents any other class from extending it.
Trying to extend it results in a fatal error:
class SampleGateway extends PaymentGateway
{
}
Fatal error: Class SampleGateway cannot extend final class PaymentGateway
final class PaymentGateway
{
public function process(): void
{
// ...
}
}
# Why Use final?
Marking a class as final communicates an important design decision: This class is complete and should not be subclassed.
This has several benefits.
1.Protect Business Logic:
Some classes contain critical logic that should never be modified through inheritance. Using final guarantees that subclasses cannot override or change the behavior.
2.Make Your API Clear:
Developers immediately understand that inheritance is not part of the public API. Instead of extending the class, they should use composition or interfaces.
3.Prevent Fragile Inheritance:
Inheritance creates tight coupling. A parent class may unintentionally break child classes after internal changes. Making a class final eliminates this risk because no subclasses can exist.
# When Should You Use final
There isn’t a universal rule, but these are common scenarios.
- Value Objects
- Service Classes
- Domain Objects with Fixed Behavior
- Internal Library Classes
# When Should You Avoid final?
Avoid marking a class as final if you expect developers to extend it.
- Framework base classes
- Abstract classes
- Extension points in packages
- Classes specifically designed for inheritance
If inheritance is part of the design, final only makes the API less useful.
# Can use final for methods too
PHP allows final on both classes and individual methods.
class Animal
{
final public function sleep(): void
{
}
}
Here:
- The class can be extended.
- The
sleep()method cannot be overridden.
When the entire class is marked final, none of its methods can be overridden because the class itself cannot be inherited.