PHP Traits is a group of methods which can be included within another class. A Trait cannot be instantiated by itself like an abstract class. Traits are generated to reduce the limitations of single inheritance in PHP. It allows a developer to reuse sets of methods freely in various independent classes living in different class hierarchies.
Example
trait Sharable {
public function share($item)
{
return ‘share this item’;
}
}
We can then include this Trait within other classes like:
class Post {
use Sharable;
}
class Comment {
use Sharable;
}
Now, if we want to create new objects out of these classes, we would find that they both have the share() method available:
$post = new Post;
echo $post->share(”); // ‘share this item’
$comment = new Comment;
echo $comment->share(”); // ‘share this item’