What are Trait in PHP ? Why do we need Trait in PHP ?
In this article we will be working on a very new feature which is introduced in PHP 5.4 which is Traits in PHP.
Traits are mechanisms which help and increase in code re-usability, and also serves perfectly to solve the problem of multiple inheritance in php.
For example we have two or more than two classes that need to access a method / function .
So to solve this before version 5.4 you were suppose to do something like :
First of we create a Log class, which would be used to save log messages
1 2 3 4 5 6 7 8 9 10 |
<?php class Log { public function log ( $message ) { // Saving $message in a log echo "log message:".$message; } } ?> |
Now we create another classes that will use this feature of saving logs, but these classes can not extend our Log class as multiple inheritance does not exist in PHP:
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 |
<?php class User { protected $varLog; public function __construct () { $this->varLog = new Log(); } public function add () { $this->varLog->log('User added'); } } class Cart { protected $varLog ; public function __construct () { $this->varLog->Log = new Log (); } public function delete () { $this->varLog->log ('delete the shopping cart'); } } ?> |
Now we have to create object of log class again and again also we can not extend the log class in multiple classes therefor we will now move on to new feature of php that is traits and we will convert our Log class to a Trait. Now exactly you will come to know What are traits in php
1 2 3 4 5 6 7 8 9 10 |
<?php Trait Log { public function log ($message) { // Saving $message in a log } } ?> |
And this is how we will use our Log Trait in our multiple classes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?php class User{ use Log; public function add() { $this-> log ( 'User created'); } } class Cart{ use Log; public function delete () { $this->log('delete the shopping cart'); } } ?> |
Now we use the log() method directly without creating any instance of class and calling it in constructor function this is because our multiple classes have accessed the characteristics (methods as well as attributes) Log Trait.
If you have any questions please post below
You can check for Official documentation here: http://php.net/traits