CHAPTER 4 ■ ADVANCED FEATURES
Final Classes and Methods
Inheritance allows for enormous flexibility within a class hierarchy. You can override a class or method
so that a call in a client method will achieve radically different effects according to which class instance it
has been passed. Sometimes, though, a class or method should remain fixed and unchanging. If you
have achieved the definitive functionality for your class or method, and you feel that overriding it can
only damage the ultimate perfection of your work, you may need the final keyword.
final puts a stop to inheritance. A final class cannot be subclassed. Less drastically, a final method
cannot be overridden.
Here's a final class:
final class Checkout {
// ...
}
Here’s an attempt to subclass the Checkout class:
class IllegalCheckout extends Checkout {
// ...
}
This produces an error:
PHP Fatal error: Class IllegalCheckout may not inherit from
final class (Checkout) in ...
I could relax matters somewhat by declaring a method in Checkout final, rather than the whole class.
The final keyword should be placed in front of any other modifiers such as protected or static, like
this:
class Checkout {
final function totalize() {
// calculate bill
}
}
I can now subclass Checkout, but any attempt to override totalize() will cause a fatal error:
class IllegalCheckout extends Checkout {
final function totalize() {
// change bill calculation
}
}
// Fatal error: Cannot override final method
// checkout::totalize() in ...
Good object-oriented code tends to emphasize the well-defined interface. Behind the interface,
though, implementations will often vary. Different classes or combinations of classes conform to
common interfaces but behave differently in different circumstances. By declaring a class or method
final, you limit this flexibility. There will be times when this is desirable, and you will see some of them