1 Answer

0 votes
by

PHP Traits are simply a group of methods that you want include within another class. 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;
 
}

Now if you were to create new objects out of these classes you 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'

Related questions

0 votes
0 votes
0 votes
    In his seminal work on genetics, Gregor Mendel described the physical traits in the pea plant as being controlled by ... (d) Hybrids Select the correct answer from above options...
asked Nov 9, 2021 in Education by JackTerrance
0 votes
    What are pros and cons of using Laravel Framework?...
asked Sep 30, 2021 in Technology by JackTerrance
0 votes
    Why are migrations necessary in laravel?...
asked Sep 30, 2021 in Technology by JackTerrance
0 votes
    What are Bundles in Laravel?...
asked Sep 30, 2021 in Technology by JackTerrance
0 votes
0 votes
    What are service providers in Laravel ?...
asked Sep 30, 2021 in Technology by JackTerrance
0 votes
    What are default packages of Laravel 5.6?...
asked Sep 28, 2021 in Technology by JackTerrance
0 votes
    What is Laravel nova?...
asked Oct 1, 2021 in Technology by JackTerrance
0 votes
    How to clear Cache in Laravel?...
asked Oct 1, 2021 in Technology by JackTerrance
0 votes
0 votes
0 votes
0 votes
    What is Dependency Injection and its types in laravel?...
asked Sep 30, 2021 in Technology by JackTerrance
...