Traits are a group of methods that can be added to classes. These classes are functional blocks that are repeatedly used in classes.
Traits are defined with a keyword trait:
trait Paint{ }
Traits can be filled with static and non-static methods:
trait Printer { public function printSimpleText($text) { echo "$text<br>"; } public function printHeaderText($text) { echo "<h2>$text<h2>"; } }
To insert trait you need add the “use” keyword
class Message { use Printer; } //now we can use the trait method $Message = new Message(); $Message->printSimpleText("Hello World!");
!when inherited, the trait methods override inherited methods with the same name: