Traits class

From Wikipedia, the free encyclopedia
Jump to: navigation, search

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

[edit] References

Personal tools
Namespaces

Variants
Actions
Navigation
Interaction
Toolbox
Print/export