Reputation: 6386
I was just playing around with traits to see what its purpose was and I noticed it allows a class to make use of multiple trait classes whereas a class extending from an abstract can extend from one abstract at a time
Here is my example:
trait parentClass
{
public function sayHello()
{
return 'parentClass sayHell() printed';
}
}
trait parentSecondClass
{
public function sayGoodbye()
{
return 'parentClass sayGoodbye() printed';
}
}
class People
{
use parentClass;
use parentSecondClass;
}
$o = new People();
echo $o->sayHello() . '<br/>';
echo $o->sayGoodbye();
Is this the general use of traits?
Upvotes: 1
Views: 147
Reputation: 60413
Generally traits are used for abstract functionality that might be needed by many classes that are not part of the same class hierarchy. You could use a trait to keep this functionality in a single location and apply it across a number of classes.
This doesn't remove the usefulness of abstract classes, but it does potentially remove the need for static utility classes one might typically put these type of functions in.
Upvotes: 4