Traits in php are the mechanism for reusing the code in a single inheritance.
Trait is as similar as a class, but only focus to group functionality in a consistent way to fine grained.
We can not instantiate a Trait . It is for reducing some limitations of single inheritance for reusing group of methods easily in different independent classes in a different class hierarchies.
We can do Multiple Traits insertion into a class by listing all in the use statement, and separated them by commas.Please note that If we insert two Traits having method with the same name, then a fatal error is produced.
Example
class BaseClass{
function getReturnType() {
return 'BaseClass';
}
}
trait traitSample {
function getReturnType() {
echo "TraitSample:";
parent::getReturnType();
}
}
class Class1 extends BaseClass {
use traitSample;
}
$obj1 = new Class1();
$obj1->getReturnType();//TraitSample:BaseClass
0 Comment(s)