I know what the definition is of a Final class, but I want to know how and when final is really needed.
<?php
final class Foo extends Bar
{
public function()
{
echo 'John Doe';
}
}
If I understand it correctly, 'final' enables it to extend 'Foo'.
Can anyone explain when and why 'final' should be used? In other words, is there any reason why a class should not be extended?
If for example class 'Bar' and class 'Foo' are missing some functionality, it would be nice to create a class which extends 'Bar'.
There is a nice article about "When to declare classes final". A few quotes from it:
TL;DR: Make your classes always
final
, if they implement an interface, and no other public methods are definedWhy do I have to use
final
?
- Preventing massive inheritance chain of doom
- Encouraging composition
- Force the developer to think about user public API
- Force the developer to shrink an object's public API
- A
final
class can always be made extensibleextends
breaks encapsulation- You don't need that flexibility
- You are free to change the code
When to avoid
final
:Final classes only work effectively under following assumptions:
- There is an abstraction (interface) that the final class implements
- All of the public API of the final class is part of that interface
If one of these two pre-conditions is missing, then you will likely reach a point in time when you will make the class extensible, as your code is not truly relying on abstractions.
P.S. Thanks to @ocramius for great reading!