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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php trait YesBoss{ public function sayIt(){ echo "Say it "; } public function hitIt(){ echo "Hit it "; } } class Boss{ public function doIt(){ echo "Do it "; } } class Manager extends Boss{ use YesBoss; public function hitIt(){ echo "Don't Hit It "; } } $worker = new Manager; $worker->sayIt(); $worker->doIt(); $worker->hitIt(); ?> |
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,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php trait Mammals{ public function sleep(){ echo "Mammals can sleep"; } } trait Birds{ public function eat(){ echo "Birds can eat"; } } class Animals{ public function sound(){ echo "Animals have sounds"; } } class Human extends Animals{ use Mammals,Birds; } $being = new Human; $being->sleep(); $being->eat(); $being->sound(); ?> |
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.

- How to build your own Youtube – Part 10 - August 1, 2016
- How to build your own Youtube – Part 9 - July 25, 2016
- How to build your own Youtube – Part 8 - July 23, 2016
- How to build your own Youtube – Part 6 - July 6, 2016
- Introducing Laravel Password v1.0 - July 3, 2016
- How to build your own Youtube – Part 5 - June 28, 2016
- How to build your own Youtube – Part 4 - June 23, 2016
- How to build your own Youtube – Part 3 - June 15, 2016
- How to build your own Youtube – Part 2 - June 8, 2016
- How to build your own Youtube – Part 1 - June 1, 2016