1.

What are traits? What problem do they solve?

Answer»

Traits are a mechanism for code reuse in single inheritance languages such as PHP. A Trait is 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.

The semantics of the combination of Traits and classes are 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 intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and ENABLES HORIZONTAL composition of behaviour; that is, the application of class members without requiring inheritance.

<?php trait Hello { function sayHello() { echo "Hello"; } } trait World { function sayWorld() { echo "World"; } } class MyWorld { use Hello, World; } $world = NEW MyWorld(); echo $world->sayHello() . " " . $world->sayWorld(); //Hello World


Discussion

No Comment Found