Traits class
In computer programming, a traits class is a class template used to associate information or behaviour to a compile-time entity, typically a data type or a constant, without modifying the existing entity. In the C++ programming language and PHP programming language, this is normally achieved by defining a primary class template, and creating explicit or partial specializations for the relevant types.
Contents |
[edit] Usage
It is used in Standard Template Library and the C++ standard library to support generic container classes. The technique is used extensively in the Boost TypeTraits library.
PHP uses this in some other way. Since version 5.4.0[1] it allows you to specify templates that are not as dynamic as C++ in using different data types but they gives you the ability to "inherit" from more than one (trait-)class.
[edit] Examples
[edit] PHP
Since version 5.4.0 PHP gives you traits. This example uses one template class (trait) to enhance another class:
// the template trait TSingleton { private static $_instance = null; public static getInstance() { if (null === static::$_instance) { static::$_instance = new static(); } return static::$_instance; } } class FrontController { use TSingleton; } // can even be used in already extended classes class WebSite extends SomeClass { use TSingleton; }
This gives you the power to "inherit" multiple functionalities:
trait TBounding { public $x, $y, $width, $height; } trait TMoveable { public function moveTo($x, $y) { // ... } } trait TResizeable { public function resize($newWidth, $newHeight) { // ... } } class Rectangle { use TBounding, TMoveable, TResizeable; function fillColor($color) { // ... } }
[edit] External links
- Generic Programming Techniques from Boost
- iterator_traits<Iterator> from SGI
- Traits: a new and useful template technique, Nathan C. Myers, C++ Report, June 1995 issue
- Traits - PHP Documentation
[edit] References
- ^ Marr, Stefan (09). "Request for Comments: Horizontal Reuse for PHP" (in English). PHP. PHP. https://wiki.php.net/rfc/horizontalreuse. Retrieved 14 January 2012.
| This computer programming-related article is a stub. You can help Wikipedia by expanding it. |