Re-iterating the Use Of Traits

For so many years now, Php Developers have always envied their Java colleagues for so many reasons which i wouldn’t be stating here to preserve my lovely life .  One of such reasons is “Multiple Inheritance”.

Php has been a single inheritance language for so long, but after so many years of praying and fasting from the Php faithfuls, the God of Php decided to bless us with a gift – Traits.

Traits are a mechanism for reusing code in Php, a cool alternative to Java’s Multiple Inheritance. As of Php 5.4.0, you can comfortably use Traits in your php applications. Let’s dive straight it to see how Traits work.

Output :  Say It Do It Don’t Hit It

Notice the precedence, class Manager has the ability to override methods from a trait which it did here in our example by overriding hitIt() method from  traits YesBoss.

class Manager also inherits from class Boss and traits yesBoss. A class can also inherit from multiple traits. For example,

Output: Mammals can sleep Birds can eat Animals have sounds.

A lot of Php developers haven’t taken hold of this powerful feature yet, ..My advice to you is use traits today, it will make your life a whole lot easier.




Food Ninja, Code Slinger, Technical Trainer, Accidental Writer, Open Source Advocate and Developer Evangelist.