A Trait is simply a group of methods that you want include within another class. A Trait, like an abstract class, cannot be instantiated on it’s own.
Usually trait is created inside a new directory called Trait and placed inside App folder.
trait TraitName{
public function traitFunc()
{
//.................
}
}
After that we can use this trait in any other class. Other class treat the trait as its own behavior. To use the traits in any other class we must take care of 2 things:
- use keyword with trait name outside class name eg: use UploadFile
- use keyword with trait name inside class name i.e. as soon as class name declaration is done
use App\Trait\TraitName;
class Post {
use TraitName;
public function anyFunctionName()
{
$this->traitFunc();
}
}