The recent release of PHP 5.4 includes a new feature called Traits. It enables method injection into classes and the concept will be familiar to anyone who has experience with Ruby’s mixins or traits in Scala. CakePHP’s ‘Model Behaviour’ functionality is also influenced by the concept of traits and mixins.
Traits are similar to abstract classes, however they are particularly useful when a method has applications across a wide area of concerns. They can be used to avoid generic abstract classes and interfaces that are often used to compensate for PHP’s lack of multiple inheritance.
In its simplest form, a trait can have no interaction with the class it is injected into:
<?php trait HelloWorld { public function helloWorld() { echo "Hello World"; } } class Person { use HelloWorld; } $person = new Person(); $person->helloWorld(); ?>
However its real power lies in retrieving and/or manipulating object properties – especially when the function could be applied to classes that have no direct similarities:
<?php trait ClassDetails { public function getClassDetails() { $className = get_class($this); $output = "Class name: $className. "; $parentClassName = get_parent_class($this); if($parentClassName === false) { $output .= "No parent class"; } else { $output .= "Parent class name: $parentClassName."; } return $output; } } class Person { use ClassDetails; } $person = new Person(); echo $person->getClassDetails(); /* returns 'Class name: Person. No parent class.' */ class MysqlConnection extends DbConnection { use ClassDetails; } $connection = new MysqlConnection(); echo $connection->getClassDetails(); /* returns 'Class name: MysqlConnection. Parent class name: DbConnection.' */ ?>
For further details on traits in PHP 5.4, see http://php.net/traits.
Trackbacks/Pingbacks