This post covers the Traits section of the OOP chapter when studying for the Zend PHP 7 Certification.

Traits, introduced in PHP 5.4.0, are a mechanism for code reuse and are intended to reduce some limitations of single inheritance by enabling a developer to reuse sets of methods freely in several independent classes living in different class hierarchies.

A Trait is similar to a class, but only intended to group functionality and as such, Traits cannot be instantiated on its own like a class can.

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.

The important thing to consider when using Traits is that they really are just pieces of code that get copied into the class, and therefore are needed if you have a situation where code from one class needs to be copied into another.

A couple of potential conflicts can arise when using Traits, one of which is when trying to change the visibility of a method within the Trait that exists in the class using the Trait.

The other potential conflict is when defining a property within a Trait. If the Trait’s property has a different visibility and value compared to the original class, a fatal error will occur.

trait T {
public $foo = 'baz';
}
class A {
public $foo = 'bar';
}
class B extends A
{
use T; // Fatal error: A and T define the same property ($foo) in the composition of B. However, the definition differs and is considered incompatible.
}

In PHP 7.0, if the property has the same visibility and value as the original class, it is allowed whereas prior to this PHP version, an E_STRICT notice would be raised.