What is a trait in Php ?

About

A trait 1) is a collection of code that is added dynamically to your class.

It helps to alleviate the limitation of class hierarchy (object inheritance) when:

  • objects should share method
  • that can't be applied to all objects (through hierarchy / inheritance).

It follows the composition principe

A trait is not a class. You can't access its members directly. It's basically just automated copy and paste.

Example: Fetch Resource with or without source

For instance, if the class inheritance represents a resource to fetch (ie returns)

  • it may be generated (for instance a snapshot of an html page)
  • or it may be the modification of a source file (image rotation)

As not all resources share this property (or trait) in the class hierarchy, you could create a trait with the respective method (get/set Source).

How-to

How to overwrite a trait method with aliasing

When importing the trait code with the use keyword, you need to create an alias for the method name that you want to overwrite and use it.

Example:

class myClass
{

    use myTrait {
        getMyVar as protected getMyVarTraitAlias;
    }
    
    public function getMyVar(){
        $var = $this->getMyVarTraitAlias();
        ...
        return $var;
    }
...
}

Powered by ComboStrap