Ramesh Thapa

Sharing my personal opinion and notes

Whats are traits in Laravel (PHP)?

PHP Traits are simply a group of methods that you want include with in another class. A traits, like an abstract class can not be instantitated by itself.

Traits are created to reduce the limitation of single inheritance in PHP by enabling a developer to reuse sets of methods freely in several independed class living in diffrent class hierarchies.

Here is example of traits in Laravel

trait Sharable {

public function share ($item)

{ return ‘share this item’ ;}

}

We can use this traits with in others class like this.

class Post {

use Sharable;

}

class Comment {

use Sharable;

}

Now if we were to create new object out of those classes, we would find that they both have the share() methods available.

$post = new Post;

echo $post->share (‘ ‘);   // share this items

 

$comment = new Comment;

echo $comment->share (‘ ‘); // share this items

 

 

Leave comment

Your email address will not be published. Required fields are marked with *.