PHP 5.4 and PHP Traits

Many ( or most ) of  PHP deverlopers know that PHP 5.4 came out with good feature called  PHP Traits.  In definition, it is summarized as below. 

Traits is 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 is defined in a way, which reduces complexity and avoids the typical problems associated with multiple inheritance and Mixins.

 

RFC for PHP Traits can be found here

Traits can be very useful for single inhertance language like PHP  ( and many others ). Single inheritance can create redudency and other issues in many cases. 

Simple Traits example

<?php
trait ezcReflectionReturnInfo 
{
    function 
getReturnType() { /*1*/ }
    function 
getReturnDescription() { /*2*/ }
}

class ezcReflectionMethod extends ReflectionMethod {
    use 
ezcReflectionReturnInfo;
    
/* … */
}

class ezcReflectionFunction extends ReflectionFunction {
    use 
ezcReflectionReturnInfo;
    
/* … */
}
?>

 

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 behavior; that is, the application of class members without requiring inheritance.

PHP Manual describes it pretty well. Find it here

When you come across sitaution to use functionality from two base classes, give “traits” a try !

 


 


1 comment to PHP 5.4 and PHP Traits

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*

Find us on Facebook

?