PHP, composition and inheritance

  |   |  3 minutes  |  527 words
PHP, composition and inheritance
Image from Pol Dellaiera

I’ve been contributing to a couple of trending php libraries recently and during the analysis and the making of the patches, noticed that many libraries were using PHP not in the way I was used to.

Many of those libraries are having ‘final’ classes.

  • Why using final classes everywhere, what is the advantage?
  • As I’m not using final classes in my own projects, am I wrong since the beginning?

This article will try to bring an explanation to this.

Just like Marco Pivetta (@ocramius) or Tomas Votruba wrote on their respective blogs, this article will basically explain the use of the final keywords.

Libraries like PHP Infection, PHPSpec, PHP-CS-Fixer are using final classes almost everywhere.

When you use the word final for a class, it means that your class will not be able to extend another one.

That means that you forbid anyone to create a class that extend your class.

The goal of creating classes is to use the amazing inheritance mechanism, why would we forbid that ?! At first, that sounds stupid, but in the end, it’s not that bad.

By doing so, you enforce users to use a proper dependency injection mechanism if they really need to use the parent class.

Since a couple of months, I’m starting use more and more composition over inheritance.

Composition is in the end much more flexible than inheritance and dependency injection is a valid way to compose a class.

However, there is a simple solution if you really need to extends a final class.

As you cannot extend a final class, the only way is to inject the final class as argument in the constructor of your class.