When to use Final in PHP?

Inga Johansson picture Inga Johansson · Nov 22, 2010 · Viewed 42.7k times · Source

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'.

Answer

Nikita U. picture Nikita U. · Nov 18, 2015

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 defined

Why do I have to use final?

  1. Preventing massive inheritance chain of doom
  2. Encouraging composition
  3. Force the developer to think about user public API
  4. Force the developer to shrink an object's public API
  5. A final class can always be made extensible
  6. extends breaks encapsulation
  7. You don't need that flexibility
  8. You are free to change the code

When to avoid final:

Final classes only work effectively under following assumptions:

  1. There is an abstraction (interface) that the final class implements
  2. 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!