- A trait is essentially PHP’s implementation of a mixin, and is effectively a set of extension methods which can be added to any class through the addition of the trait. The methods then become part of that class’ implementation, but without using inheritance.
- An interface defines a set of methods that the implementing class must implement.
Consider:
trait myTrait {
function foo() { return "Foo!"; }
function bar() { return "Bar!"; }
}
class MyClass extends SomeBaseClass {
use myTrait; // Inclusion of the trait myTrait
}
PHP, like many other languages, uses a single inheritance model – meaning that a class can derive from multiple interfaces, but not multiple classes. However, a PHP class can have multiple trait inclusions – which allows the programmer to include reusable pieces – as they might if including multiple base classes.