Is that joke old yet? Anyway, with PHP 5.4 officially released yesterday, I’m very excited about the new traits implementation which, in a nutshell, allows a class to import specific functionality in the form of implemented methods.
In my post on interfaces, I explained that interfaces are like a contract, promising to deliver specific functionality without promising exactly how they will deliver it. Traits take it a step further, providing a contract that not only promises functionality, but also specifies an implementation, to be mixed in to or “exhibited” by concrete classes. To borrow an old example:
protected $tags = array();
public function tag($tag)
$this->tags = $tag;
// other methods implemented by the class
In the example above, instantiations of
FooObject would have access to the
tag() method imported from the
Taggable trait. This is a very powerful feature, one which will provide a workaround to some of the limitations of PHP’s single inheritance hierarchy and let developers create an even more powerful toolkit of code snippets to call on, reducing development time and (hopefully) increasing productivity.
And that’s not all that 5.4 is bringing to the table. Here’s a pithy tweet summing up the new release: