traits code example

Example: traits

A Trait, like an abstract class cannot be instantiated by itself.Trait are created to reduce the limitations of single inheritance in PHP by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

Here is an example of trait.

trait Sharable {
 
  public function share($item)
  {
    return 'share this item';
  }
 
}
You could then include this Trait within other classes like this:


class Post {
 
  use Sharable;
 
}
 
class Comment {
 
  use Sharable;
 
}

Tags:

Php Example