Why I don't like PHP traits

PHP evolved a lot recently, mostly with PHP 5.3. A lot of new features appeared (closures, namespaces, syntactic sugars...), and I'm really happy with most of them.

One of these features is called traits. The principle is to be able to "import" some code in classes, just like this:


trait Gentleman {
    public function sayHello() {
        echo "Hello!\n";

class Bob {
    use Gentleman;

$bob = new Bob;

Traits are just like copy and paste of some code you want to have in your class. I think they did that because PHP don't implements multiple inheritance, so if one of your class is already extending another one in your application, you don't have other ways to "import" behaviors in it.

There is mainly two problems with that:

  • Traits are not part of the object paradigms. For instance you can't really represent it on a designing diagram. Multiple inheritance is part of the object paradigms.
  • Traits are a little like multiple inheritance, triggering the same problems as inheritance, because you may have to deal with naming conflict when using multiple traits, but are not multiple inheritance

Why PHP is not implementing actual multiple inheritance, instead of proposing this strange patch?

This article is my 9th oldest. It is 50 words long