What is "trait"

Traits are a mechanism for code reuse in simple inheritance languages. Its goal is to reduce some simple inheritance limitations by allowing reuse sets of methods freely in various independent classes living in different class hierarchies. The semantics of the combination of characteristics and classes is defined in a way that reduces complexity, and avoids the typical problems associated with multiple inheritance and mixins.

A trait is similar to a class, but only an intention of functionality in a refined and consistent way. Cannot instantiate a dash on its own. It is an addition to traditional heritage and allows the horizontal framing of behavior, i.e., the application of class members without the need for inheritance.


Example of use in PHP

As of PHP 5.4.0, PHP implements Traits as a code reuse method.

trait HelloWorld {
    public function sayWorld() {
        echo 'Hello World!';
    }
}

class TheWorldIsNotEnough {
    use HelloWorld;
    public function sayUniverse() {
        echo 'Hello Universe!';
    }
}

The example below prints: Hello Universe!

$class = new TheWorldIsNotEnough();
$class-> sayUniverse();

The example below prints: Hello World!

$class = new TheWorldIsNotEnough();
$class-> sayWorld();