PHP Traits: When To Use And Why

Vitaliy Dotsenko
Legacybeta
Published in
2 min readJul 3, 2020
Photo by Larry Nalzaro on Unsplash

Since PHP version 5.4.0 the language has had the keyword — trait. The main purpose of PHP Traits is to solve the single inheritance limitations of the language, because in PHP you can't do extends Class1, Class2. Traits contain a declaration of the methods or the properties that you can easily apply to the classes using the keyword use.

trait SomeTrait
{
public function traitMethod()
{
// ...
}
}
class SomeClass
{
use SomeTrait;

public function method()
{
// You have access to the Trait method $this->traitMethod();
}
}

PHP has the function class_uses() that allows you to get the array of Traits that are used:

class_uses(SomeClass::class)

Use cases

The shared code can be placed into a Trait to prevent duplicates of the code and use a Trait easily in your classes. Laravel uses this technique everywhere :)

Using Traits in Laravel makes it easy to get your model to work with a full-text search engine simply by adding the line use Searchable into the model.

Laravel Nova uses the Actionable trait to log the Action activity of your Eloquent model.

But be careful a Trait can’t be “de-use” (disabled). If you need to have a class that uses a Trait and sometime you’ll decide to use this class somewhere without Trait just decompose it into parts using inheritance and an abstract class. For example, you have the Searchable trait and you want to have the Product class without this Trait:

abstract AbstractProduct
{
// The product properties and methods
}
class Product extends AbstractProduct
{
use Searchable;
}
class ProductWithoutSeachable extends AbstractProduct
{
// Nothing here
}

The properties

As I said, the trait can contain more than methods, it also can contain a definition of properties:

trait SomeTrait
{
private $value;
}

The private visibility of the property will be applied to the class which will use this Trait.

Resolve naming conflicts

If you have similar names of the methods in the Trait and class and you want to call the method from the Trait in the class, you can resolve it by creating alias using the keyword as.

For example, the Trait and the class have the method doSomething and you want to call the doSomething which in the Trait from the class method doSomething:

trait SomeTrait
{
public function doSomething()
{
echo 'doSomething from trait' . PHP_EOL;
}
}
class SomeClass
{
use SomeTrait {
doSomething as traitDoSomething;
}

public function doSomething()
{
$this->traitDoSomething();
echo 'doSomething from class' . PHP_EOL;
}
}
$obj = new SomeClass();
$obj->doSomething();

The output of the above code:

doSomething from trait
doSomething from class

I hope after reading the article you know more than you knew before about the power of Traits in PHP.

--

--

Vitaliy Dotsenko
Legacybeta

I like coding, open-source software and hi-tech 🚀