Defining a trait is very similar to defining a class. Instead of using the keyword class we use the keyword trait. The purpose of traits is to group functionality in a fine grained and consistent way. It is not possible to instantiate a trait. The trait servers as an additional capability that provides us with additional capabilities when using inheritance in our code. The class we define can extend one class at the most and implement interfaces and/or uses traits as many as we want. The following video clip shows a simple trait definition.
<?php trait Academic { function think() { echo "i m thinking!"; } } class Person { private $id; private $name; function __construct($idValue,$nameValue) { $this->id = $idValue; $this->name = $nameValue; } function __toString() { return "id=".$this->id." name=".$this->name; } } class Student extends Person { use Academic; private $avg; function __construct($idVal,$nameVal,$avgVal) { parent::__construct($idVal,$nameVal); $this->avg = $avgVal; } function __toString() { $str = parent::__toString(); return "avg=".$this->avg.$str; } } class Lecturer extends Person { private $degree; function __construct($idVal,$nameVal,$degreeVal) { parent::__construct($idVal,$nameVal); $this->degree = $degreeVal; } function __toString() { $str = parent::__toString(); return "degree=".$this->degree.$str; } use Academic; } $student = new Student(123123,"mosh",98); $lecturer = new Lecturer(42343,"dan","mba"); $student->think(); echo "<hr/>"; $lecturer->think(); ?>
The following video clip shows the execution of this code sample and explains it.