类与对象
在线手册:中文 英文
PHP手册

Traits

As of PHP 5.4.0, PHP implements a method of code reuse called Traits.

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.

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.

Example #1 Trait example

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

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

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

Precedence

An inherited member from a base class is overridden by a member inserted by a Trait. The precedence order is that members from the current class override Trait methods, which in return override inherited methods.

Example #2 Precedence Order Example

An inherited method from a base class is overridden by the method inserted into MyHelloWorld from the SayWorld Trait. The behavior is the same for methods defined in the MyHelloWorld class. The precedence order is that methods from the current class override Trait methods, which in turn override methods from the base class.

<?php
class Base {
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait SayWorld {
    public function 
sayHello() {
        
parent::sayHello();
        echo 
'World!';
    }
}

class 
MyHelloWorld extends Base {
    use 
SayWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
?>

以上例程会输出:

Hello World!

Example #3 Alternate Precedence Order Example

<?php
trait HelloWorld 
{
    public function 
sayHello() {
        echo 
'Hello World!';
    }
}

class 
TheWorldIsNotEnough {
    use 
HelloWorld;
    public function 
sayHello() {
        echo 
'Hello Universe!';
    }
}

$o = new TheWorldIsNotEnough();
$o->sayHello();
?>

以上例程会输出:

Hello Universe!

Multiple Traits

Multiple Traits can be inserted into a class by listing them in the use statement, separated by commas.

Example #4 Multiple Traits Usage

<?php
trait Hello 
{
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait World {
    public function 
sayWorld() {
        echo 
'World';
    }
}

class 
MyHelloWorld {
    use 
HelloWorld;
    public function 
sayExclamationMark() {
        echo 
'!';
    }
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
$o->sayExclamationMark();
?>

以上例程会输出:

Hello World!

Conflict Resolution

If two Traits insert a method with the same name, a fatal error is produced, if the conflict is not explicitly resolved.

To resolve naming conflicts between Traits used in the same class, the insteadof operator needs to be used to chose exactly one of the conflicting methods.

Since this only allows one to exclude methods, the as operator can be used to allow the inclusion of one of the conflicting methods under another name.

Example #5 Conflict Resolution

In this example, Talker uses the traits A and B. Since A and B have conflicting methods, it defines to use the variant of smallTalk from trait B, and the variant of bigTalk from trait A.

The Aliased_Talker makes use of the as operator to be able to use B's bigTalk implementation under an additional alias talk.

<?php
trait A 
{
    public function 
smallTalk() {
        echo 
'a';
    }
    public function 
bigTalk() {
        echo 
'A';
    }
}

trait B {
    public function 
smallTalk() {
        echo 
'b';
    }
    public function 
bigTalk() {
        echo 
'B';
    }
}

class 
Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
    }
}

class 
Aliased_Talker {
    use 
A{
        
B::smallTalk insteadof A;
        
A::bigTalk insteadof B;
        
B::bigTalk as talk;
    }
}
?>

Changing Method Visibility

Using the as syntax, one can also adjust the visibility of the method in the exhibiting class.

Example #6 Changing Method Visibility

<?php
trait HelloWorld 
{
    public function 
sayHello() {
        echo 
'Hello World!';
    }
}

// Change visibility of sayHello
class MyClass1 {
    use 
HelloWorld sayHello as protected; }
}

// Alias method with changed visibility
// sayHello visibility not changed
class MyClass2 {
    use 
HelloWorld sayHello as private myPrivateHello; }
}
?>

Traits Composed from Traits

Just as classes can make use of traits, so can other traits. By using one or more traits in a trait definition, it can be composed partially or entirely of the members defined in those other traits.

Example #7 Traits Composed from Traits

<?php
trait Hello 
{
    public function 
sayHello() {
        echo 
'Hello ';
    }
}

trait World {
    public function 
sayWorld() {
        echo 
'World!';
    }
}

trait HelloWorld {
    use 
HelloWorld;
}

class 
MyHelloWorld {
    use 
HelloWorld;
}

$o = new MyHelloWorld();
$o->sayHello();
$o->sayWorld();
?>

以上例程会输出:

Hello World!

Abstract Trait Members

Traits support the use of abstract methods in order to impose requirements upon the exhibiting class.

Example #8 Express Requirements by Abstract Methods

<?php
trait Hello 
{
    public function 
sayHelloWorld() {
        echo 
'Hello'.$this->getWorld();
    }
    abstract public function 
getWorld();
}

class 
MyHelloWorld {
    private 
$world;
    use 
Hello;
    public function 
getWorld() {
        return 
$this->world;
    }
    public function 
setWorld($val) {
        
$this->world $val;
    }
}
?>

Static Trait Members

Static variables can be referred to in trait methods, but cannot be defined by the trait. Traits can, however, define static methods for the exhibiting class.

Example #9 Static Variables

<?php
trait Counter 
{
    public function 
inc() {
        static 
$c 0;
        
$c $c 1;
        echo 
"$c\n";
    }
}

class 
C1 {
    use 
Counter;
}

class 
C2 {
    use 
Counter;
}

$o = new C1(); $o->inc(); // echo 1
$p = new C2(); $p->inc(); // echo 1
?>

Example #10 Static Methods

<?php
trait StaticExample 
{
    public static function 
doSomething() {
        return 
'Doing something';
    }
}

class 
Example {
    use 
StaticExample;
}

Example::doSomething();
?>

Properties

Traits can also define properties.

Example #11 Defining Properties

<?php
trait PropertiesTrait 
{
    public 
$x 1;
}

class 
PropertiesExample {
    use 
PropertiesTrait;
}

$example = new PropertiesExample;
$example->x;
?>

If a trait defines a property then a class can not define a property with the same name, otherwise an error is issued. It is an E_STRICT if the class definition is compatible (same visibility and initial value) or fatal error otherwise.

Example #12 Conflict Resolution

<?php
trait PropertiesTrait 
{
    public 
$same true;
    public 
$different false;
}

class 
PropertiesExample {
    use 
PropertiesTrait;
    public 
$same true// Strict Standards
    
public $different true// Fatal error
}
?>

类与对象
在线手册:中文 英文
PHP手册
PHP手册 - N: Traits

用户评论:

Anonymous (28-Mar-2012 05:30)

Traits can not implement interfaces.
(should be obvious, but tested is tested)

Safak Ozpinar / safakozpinar at gmail (18-Mar-2012 11:03)

Unlike inheritance; if a trait has static properties, each class using that trait has independent instances of those properties.

Example using parent class:
<?php
class TestClass {
    public static
$_bar;
}
class
Foo1 extends TestClass { }
class
Foo2 extends TestClass { }
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo
Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
?>

Example using trait:
<?php
trait TestTrait
{
    public static
$_bar;
}
class
Foo1 {
    use
TestTrait;
}
class
Foo2 {
    use
TestTrait;
}
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo
Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: Hello World
?>

Jason dot Hofer dot deletify dot this dot part at gmail dot com (15-Mar-2012 12:39)

A (somewhat) practical example of trait usage.

Without traits:

<?php

class Controller {
 
/* Controller-specific methods defined here. */
}

class
AdminController extends Controller {
 
/* Controller-specific methods inherited from Controller. */
  /* Admin-specific methods defined here. */
}

class
CrudController extends Controller {
 
/* Controller-specific methods inherited from Controller. */
  /* CRUD-specific methods defined here. */
}

class
AdminCrudController extends CrudController {
 
/* Controller-specific methods inherited from Controller. */
  /* CRUD-specific methods inherited from CrudController. */
  /* (!!!) Admin-specific methods copied and pasted from AdminController. */
}

?>

With traits:

<?php

class Controller {
 
/* Controller-specific methods defined here. */
}

class
AdminController extends Controller {
 
/* Controller-specific methods inherited from Controller. */
  /* Admin-specific methods defined here. */
}

trait CrudControllerTrait {
 
/* CRUD-specific methods defined here. */
}

class
AdminCrudController extends AdminController {
  use
CrudControllerTrait;
 
/* Controller-specific methods inherited from Controller. */
  /* Admin-specific methods inherited from AdminController. */
  /* CRUD-specific methods defined by CrudControllerTrait. */
}

?>

farhad dot peb at gmail dot com (10-Mar-2012 03:29)

<?php
trait first_trait
 
{
    function
first_function()
    {
      echo
"From First Trait";
    }
  }
 
 
trait second_trait
 
{
    function
first_function()
    {
      echo
"From Second Trait";
    }
  }
 
  class
first_class
 
{
    use
first_trait, second_trait
   
{
     
// This class will now call the method
      // first function from first_trait only
     
first_trait::first_function insteadof second_trait;
 
     
// first_function of second_traits can be
      // accessed with second_function
     
second_trait::first_function as second_function;
 
    }
  }
 
 
$obj = new first_class();
 
// Output: From First Trait
 
$obj->first_function();
 
 
// Output: From Second Trait
 
$obj->second_function();
?>

the iranian php programmer

writer: farhad zand

farhad.peb@gmail.com
php_engineer_bk@yahoo.com

brutallord (07-Mar-2012 06:53)

really useful construction to evade code duplication

anthony bishopric (03-Mar-2012 08:11)

The magic method __call works as expected using traits.

<?php
trait Call_Helper
{
   
    public function
__call($name, $args){
        return
count($args);
    }
}

class
Foo{
    use
Call_Helper;
}

$foo = new Foo();
echo
$foo->go(1,2,3,4); // echoes 4

Anonymous (02-Mar-2012 05:44)

To answer [simoncpu was here 29-Feb-2012 08:54]: multiple inheritance isn't supported in PHP. See http://www.php.net/manual/en/language.oop5.basic.php section "extends": "It is not possible to extend multiple classes; a class can only inherit from one base class."

Edward (01-Mar-2012 11:29)

The difference between Traits and multiple inheritance is in the inheritance part.   A trait is not inherited from, but rather included or mixed-in, thus becoming part of "this class".   Traits also provide a more controlled means of resolving conflicts that inevitably arise when using multiple inheritance in the few languages that support them (C++).  Most modern languages are going the approach of a "traits" or "mixin" style system as opposed to multiple-inheritance, largely due to the ability to control ambiguities if a method is declared in multiple "mixed-in" classes.

Also, one can not "inherit" static member functions in multiple-inheritance.

simoncpu was here (29-Feb-2012 04:54)

Can anyone please enlighten me on the difference between traits and multiple inheritance?

Why can't we just do this:

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

class
ezcReflectionMethod extends ReflectionMethod, ezcReflectionReturnInfo {
   
/* ... */
}

class
ezcReflectionFunction extends ReflectionFunction, ezcReflectionReturnInfo {
   
/* ... */
}
?>

greywire at gmail dot com (17-Feb-2012 03:12)

The best way to understand what traits are and how to use them is to look at them for what they essentially are:  language assisted copy and paste.

If you can copy and paste the code from one class to another (and we've all done this, even though we try not to because its code duplication) then you have a candidate for a trait.

chris dot rutledge at gmail dot com (21-Dec-2011 08:42)

It may be worth noting here that the magic constant __CLASS__ becomes even more magical - __CLASS__ will return the name of the class in which the trait is being used.

for example

<?php
trait sayWhere
{
    public function
whereAmI() {
        echo
__CLASS__;
    }
}

class
Hello {
    use
sayWHere;
}

class
World {
    use
sayWHere;
}

$a = new Hello;
$a->whereAmI(); //Hello

$b = new World;
$b->whereAmI(); //World
?>

The magic constant __TRAIT__ will giev you the name of the trait