트레이트

PHP 5.4.0 부터, 트레이트 라는 코드 재사용 방법을 구현했습니다.

트레이트는 PHP와 같은 단일상속 언어를 위한 코드 재사용 기법입니다. 트레이트는 단일상속의 몇가지 한계를 줄이기 위해 고안되었습니다. 개발자들은 서로 다른 클래스 계층구조를 가지는 독립 클래스들에서 자유롭게 메서드셋을 재사용할수 있습니다. 트레이트와 클래스의 조합에 대한 의의는 복잡성을 줄이고, 다중상속과 믹스인(Mixin)과 연관된 통상적인 문제를 줄이는데 있습니다.

트레이트는 클래스와 비슷하지만, 매끄럽고 일관된 방법으로 기능을 그룹화하기 위해 고안되었습니다. 트레이트는 자신을 인스턴스화할 수 없습니다. 트레이트는 기존의 상속을 확장하고, 수평적으로 동작을 내재화 할수 있도록 합니다. 이말은, 상속없이 클래스 멤버에 추가할수 있음을 의미합니다.

Example #1 트레이트 예제

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

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

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

우선순위

기본 클래스로부터 상속된 멤버는 트레이트의 의해 추가된 멤버에 의한 방법이 우선 됩니다. 우선순위는 현재 클래스의 멤버를 트레이트의 메서드로 재정의하고, 그 다음이 상속된 메서드를 재정의하는 순서입니다.

Example #2 우선순위 예제

기본 클래스로부터 상속된 메서드는 MyHelloWorld 에 추가된 SayWorld 트레이트의 메서드의해 재정의됩니다. MyHelloWord 클래스에 메서드가 정의된것과 같이 동작합니다. 우선순위는 현재클래스의 메서드를 트레이트 메서드로 재정의하고, 그 다음으로 기본 클래스의 메서드를 재정의하는 순서입니다.

<?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 다른 우선순위 예제

<?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!

다중 트레이트

다중 트레이트는 콤마로 구분하여 클래스에 삽입될수 있습니다.

Example #4 다중 트레이트 사용법

<?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!

충돌 해결

같은 메서드 이름을 가진 트레이트가 삽입된다면, 충돌이 명시적으로 해결되지 않는한 치명적인(fatal) 에러가 날것입니다.

동일 클래스내에서 트레이트들간의 이름 충돌을 해결하기 위해서는, insteadof 연산자로 확실하게 사용할 메서드를 골라줄 필요가 있습니다.

이 방법은 다른 메서드들을 배제하고 하나의 메서드만 허용합니다. as 연산자를 사용하면 충돌되는 메서드를 다른 이름을 사용하여 포함할수 있습니다.

Example #5 충돌 해결 예제

이 예제에서, Talker는 트레이트 A와 B를 사용합니다. A와 B의 메서드가 충돌하지만, 트레이트 B의 smallTalk와 트레이트 A의 bigTalk의 사용하도록 정의 합니다.

Aliased_Talker는 as 연산자를 사용하여 B의 bigTalk 구현을 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;
    }
}
?>

메서드 가시성 변경

as 구문을 사용하여, 가시성 또한 조정할 수 있습니다.

Example #6 메서드 가시성 변경 예제

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

// sayHello 가시성 변경
class MyClass1 {
    use 
HelloWorld sayHello as protected; }
}

// 메서드를 별칭을 지정하여 가시성을 변경하면
// sayHello 의 가시성은 변경되지 않습니다.
class MyClass2 {
    use 
HelloWorld sayHello as private myPrivateHello; }
}
?>

트레이트로 조합된 트레이트

클래스들이 트레이트를 사용할수 있는것처럼 트레이트도 트레이트를 사용할 수 있습니다. 하나 또는 여러 트레이트를 하나의 트레이트로 정의하기 위해서, 부분적 혹은 전체적으로 조합할 수 있습니다.

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!

추상 트레이트 멤버

트레이트는 클래스의 요구사항을 강요하기위해 추상 메서드의 사용을 지원합니다.

Example #8 추상 메서드에 의한 요구사항 표현

<?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;
    }
}
?>

정적 트레이트 멤버

트레이트는 정적 멤버와 정적 메서드로 정의 가능합니다.

Example #9 정적 변수

<?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 정적 메서드

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

class 
Example {
    use 
StaticExample;
}

Example::doSomething();
?>

프로퍼티

트레이트는 프로퍼티를 정의할 수 있습니다.

Example #11 프로퍼티 정의

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

class 
PropertiesExample {
    use 
PropertiesTrait;
}

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

트레이트가 프로퍼티를 정의하면 클래스는 같은 이름으로 프로퍼티를 정의할수 없습니다. 그렇지 않을 경우 에러가 발생합니다. E_STRICT 는 클래스 정의가 동일할때(같은 가시성과 초기값을 가진경우) 발생하며, 그렇지 않을경우에는 치명적인 에러가 발생합니다.

Example #12 충돌 해결

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

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

User Contributed Notes 45 notes

up
480
Safak Ozpinar / safakozpinar at gmail
7 years ago
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
?>
up
317
greywire at gmail dot com
7 years ago
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.
up
186
Stefan W
6 years ago
Note that the "use" operator for traits (inside a class) and the "use" operator for namespaces (outside the class) resolve names differently. "use" for namespaces always sees its arguments as absolute (starting at the global namespace):

<?php
namespace Foo\Bar;
use
Foo\Test// means \Foo\Test - the initial \ is optional
?>

On the other hand, "use" for traits respects the current namespace:

<?php
namespace Foo\Bar;
class
SomeClass {
    use
Foo\Test;   // means \Foo\Bar\Foo\Test
}
?>

Together with "use" for closures, there are now three different "use" operators. They all mean different things and behave differently.
up
3
rawsrc
1 year ago
About the (Safak Ozpinar / safakozpinar at gmail)'s great note, you can still have the same behavior than inheritance using trait with this approach :
<?php

trait TestTrait {
    public static
$_bar;
}

class
FooBar {
    use
TestTrait;
}

class
Foo1 extends FooBar {

}
class
Foo2 extends FooBar {

}
Foo1::$_bar = 'Hello';
Foo2::$_bar = 'World';
echo
Foo1::$_bar . ' ' . Foo2::$_bar; // Prints: World World
up
64
atorich at gmail dot com
6 years ago
add to "chris dot rutledge at gmail dot com":
__CLASS__ will return the name of the class in which the trait is being used (!) not the class in which trait method is being called:

<?php
trait TestTrait {
    public function
testMethod() {
        echo
"Class: " . __CLASS__ . PHP_EOL;
        echo
"Trait: " . __TRAIT__ . PHP_EOL;
    }
}

class
BaseClass {
    use
TestTrait;
}

class
TestClass extends BaseClass {

}

$t = new TestClass();
$t->testMethod();

//Class: BaseClass
//Trait: TestTrait
up
72
chris dot rutledge at gmail dot com
7 years ago
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
up
36
qeremy (!) gmail
4 years ago
Keep in mind; "final" keyword is useless in traits when directly using them, unlike extending classes / abstract classes.

<?php
trait Foo {
    final public function
hello($s) { print "$s, hello!"; }
}
class
Bar {
    use
Foo;
   
// Overwrite, no error
   
final public function hello($s) { print "hello, $s!"; }
}

abstract class
Foo {
    final public function
hello($s) { print "$s, hello!"; }
}
class
Bar extends Foo {
   
// Fatal error: Cannot override final method Foo::hello() in ..
   
final public function hello($s) { print "hello, $s!"; }
}
?>

But this way will finalize trait methods as expected;

<?php
trait FooTrait {
    final public function
hello($s) { print "$s, hello!"; }
}
abstract class
Foo {
    use
FooTrait;
}
class
Bar extends Foo {
   
// Fatal error: Cannot override final method Foo::hello() in ..
   
final public function hello($s) { print "hello, $s!"; }
}
?>
up
11
marko at newvibrations dot net
3 years ago
As already noted, static properties and methods in trait could be accessed directly using trait. Since trait is language assisted c/p, you should be aware that static property from trait will be initialized to the value trait property had in the time of class declaration.

Example:

<?php

trait Beer {
    protected static
$type = 'Light';
    public static function
printed(){
        echo static::
$type.PHP_EOL;
    }
    public static function
setType($type){
        static::
$type = $type;
    }
}

class
Ale {
    use
Beer;
}

Beer::setType("Dark");

class
Lager {
    use
Beer;
}

Beer::setType("Amber");

header("Content-type: text/plain");

Beer::printed();  // Prints: Amber
Ale::printed();   // Prints: Light
Lager::printed(); // Prints: Dark

?>
up
60
t8 at AT pobox dot com
7 years ago
Another difference with traits vs inheritance is that methods defined in traits can access methods and properties of the class they're used in, including private ones.

For example:
<?php
trait MyTrait
{
  protected function
accessVar()
  {
    return
$this->var;
  }

}

class
TraitUser
{
  use
MyTrait;

  private
$var = 'var';

  public function
getVar()
  {
    return
$this->accessVar();
  }
}

$t = new TraitUser();
echo
$t->getVar(); // -> 'var'                                                                                                                                                                                                                         

?>
up
18
canufrank
3 years ago
A number of the notes make incorrect assertions about trait behaviour because they do not extend the class.

So, while "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
?>"

shows a correct example, simply adding
<?php
require_once('above');
class
Foo3 extends Foo2 {
}
Foo3::$_bar = 'news';
echo
Foo1::$_bar . ' ' . Foo2::$_bar . ' ' . Foo3::$_bar;

// Prints: Hello news news

I think the best conceptual model of an incorporated trait is an advanced insertion of text, or as someone put it "language assisted copy and paste." If Foo1 and Foo2 were defined with $_bar, you would not expect them to share the instance. Similarly, you would expect Foo3 to share with Foo2, and it does.

Viewing this way explains away a lot of  the 'quirks' that are observed above with final, or subsequently declared private vars,
up
13
Vasyl Sovyak
4 years ago
<?php
trait A
{
    public function
bar()
    {
        echo
'A::bar';
    }
}

trait
B
{
    public function
bar()
    {
        echo
'B::bar';
    }
}

trait
C
{
    public function
bar()
    {
        echo
'C::bar';
    }
}

class
Foo
{
    use
A, B, C {
       
C::bar insteadof A, B;
    }
}

$foo = new Foo();
$foo->bar(); //C::bar
up
39
karolis at iwsolutions dot ie
7 years ago
Not very obvious but trait methods can be called as if they were defined as static methods in a regular class

<?php
trait Foo {
    function
bar() {
        return
'baz';
    }
}

echo
Foo::bar(),"\\n";
?>
up
44
Anonymous
7 years ago
Traits can not implement interfaces.
(should be obvious, but tested is tested)
up
21
anthony bishopric
7 years ago
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
up
2
yeu_ym at yahoo dot com
9 months ago
Here is an example how to work with visiblity and conflicts.

<?php

trait A
{
    private function
smallTalk()
    {
        echo
'a';
    }

    private function
bigTalk()
    {
        echo
'A';
    }
}

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

    private function
bigTalk()
    {
        echo
'B';
    }
}

trait
C
{
    public function
smallTalk()
    {
        echo
'c';
    }

    public function
bigTalk()
    {
        echo
'C';
    }
}

class
Talker
{
    use
A, B, C {
       
//visibility for methods that will be involved in conflict resolution
       
B::smallTalk as public;
       
A::bigTalk as public;

       
//conflict resolution
       
B::smallTalk insteadof A, C;
       
A::bigTalk insteadof B, C;

       
//aliases with visibility change
       
B::bigTalk as public Btalk;
       
A::smallTalk as public asmalltalk;
       
       
//aliases only, methods already defined as public
       
C::bigTalk as Ctalk;
       
C::smallTalk as cmallstalk;
    }

}

(new
Talker)->bigTalk();//A
(new Talker)->Btalk();//B
(new Talker)->Ctalk();//C

(new Talker)->asmalltalk();//a
(new Talker)->smallTalk();//b
(new Talker)->cmallstalk();//c
up
6
tz at za-ek dot ru
1 year ago
I want to make flexible module that contains different functionality and I want to combine this but using the same methods:

<?php
class Brain {
    public function
ask($q) {
       
// Trate the question
       
return 'Some response';
    }
}

trait
BrainLogger {
    public function
ask($q) {
       
log('Received a question: ' . $q);
        return
parent::ask();
    }
}
trait
BrainMad {
    public function
ask($q) {
        if(
rand(0,1) == 1) {
               return
parent::ask($q);      
        } else {
               return
'I don\'t wanna talk with you.';
        }
    }
}
?>

In some part of my application I want to use different combinations of that functionality so if I want one brain instance:

<?php
$brain
= new Brain;
$brain->ask('what we gonna do tonight?');
?>

If I want log all received questions:

<?php
class NiceBrain extends Brain {
    use
BrainLog;
}
$brain = new Brain;
$brain->ask('what we gonna do tonight?'); // Will log
?>

If I want to extend more I need to make a cascade of classes:
<?php
class NiceBrain extends Brain {
    use
BrainLog;
}
class
CrazyBrain extends NiceBrain {
    use
BrainMad;
}
$brain = new CrazyBrain;
$brain->ask('What we gonna do tonight?');
// Will output  'I don't wanna talk with you.' or normal response
// but logging only in case BrainMad has a good mood
?>

Because using of multiple traits will call only one selected in section "use Trait;".
up
4
balbuf
3 years ago
(It's already been said, but for the sake of searching on the word "relative"...)

The "use" keyword to import a trait into a class will resolve relative to the current namespace and therefore should include a leading slash to represent a full path, whereas "use" at the namespace level is always absolute.
up
10
qschuler at neosyne dot com
5 years ago
Note that you can omit a method's inclusion by excluding it from one trait in favor of the other and doing the exact same thing in the reverse way.

<?php

trait A {
    public function
sayHello()
    {
        echo
'Hello from A';
    }

    public function
sayWorld()
    {
        echo
'World from A';
    }
}

trait
B {
    public function
sayHello()
    {
        echo
'Hello from B';
    }

    public function
sayWorld()
    {
        echo
'World from B';
    }
}

class
Talker {
    use
A, B {
       
A::sayHello insteadof B;
       
A::sayWorld insteadof B;
       
B::sayWorld insteadof A;
    }
}

$talker = new Talker();
$talker->sayHello();
$talker->sayWorld();

?>

The method sayHello is imported, but the method sayWorld is simply excluded.
up
15
Edward
7 years ago
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.
up
39
ryan at derokorian dot com
7 years ago
Simple singleton trait.

<?php

trait singleton {   
   
/**
     * private construct, generally defined by using class
     */
    //private function __construct() {}
   
   
public static function getInstance() {
        static
$_instance = NULL;
       
$class = __CLASS__;
        return
$_instance ?: $_instance = new $class;
    }
   
    public function
__clone() {
       
trigger_error('Cloning '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }
   
    public function
__wakeup() {
       
trigger_error('Unserializing '.__CLASS__.' is not allowed.',E_USER_ERROR);
    }
}

/**
* Example Usage
*/

class foo {
    use
singleton;
   
    private function
__construct() {
       
$this->name = 'foo';
    }
}

class
bar {
    use
singleton;
   
    private function
__construct() {
       
$this->name = 'bar';
    }
}

$foo = foo::getInstance();
echo
$foo->name;

$bar = bar::getInstance();
echo
$bar->name;
up
3
cody at codysnider dot com
2 years ago
/*
DocBlocks pertaining to the class or trait will NOT be carried over when applying the trait.

Results trying a couple variations on classes with and without DocBlocks that use a trait with a DocBlock
*/

<?php

/**
* @Entity
*/
trait Foo
{
    protected
$foo;
}

/**
* @HasLifecycleCallbacks
*/
class Bar
{
    use \
Foo;
   
    protected
$bar;
}

class
MoreBar
{
    use \
Foo;
   
    protected
$moreBar;
}

$w = new \ReflectionClass('\Bar');
echo
$w->getName() . ":\r\n";
echo
$w->getDocComment() . "\r\n\r\n";

$x = new \ReflectionClass('\MoreBar');
echo
$x->getName() . ":\r\n";
echo
$x->getDocComment() . "\r\n\r\n";

$barObj = new \Bar();
$y = new \ReflectionClass($barObj);
echo
$y->getName() . ":\r\n";
echo
$y->getDocComment() . "\r\n\r\n";

foreach(
$y->getTraits() as $traitObj) {
    echo
$y->getName() . " ";
    echo
$traitObj->getName() . ":\r\n";
    echo
$traitObj->getDocComment() . "\r\n";
}

$moreBarObj = new \MoreBar();
$z = new \ReflectionClass($moreBarObj);
echo
$z->getName() . " ";
echo
$z->getDocComment() . "\r\n\r\n";

foreach(
$z->getTraits() as $traitObj) {
    echo
$z->getName() . " ";
    echo
$traitObj->getName() . ":\r\n";
    echo
$traitObj->getDocComment() . "\r\n";
}
up
16
Jason dot Hofer dot deletify dot this dot part at gmail dot com
7 years ago
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. */
}

?>
up
13
Kristof
5 years ago
don't forget you can create complex (embedded) traits as well

<?php
trait Name {
 
// ...
}
trait
Address {
 
// ...
}
trait
Telephone {
 
// ...
}
trait
Contact {
  use
Name, Address, Telephone;
}
class
Customer {
  use
Contact;
}
class
Invoce {
  use
Contact;
}
?>
up
13
D. Marti
7 years ago
Traits are useful for strategies, when you want the same data to be handled (filtered, sorted, etc) differently.

For example, you have a list of products that you want to filter out based on some criteria (brands, specs, whatever), or sorted by different means (price, label, whatever). You can create a sorting trait that contains different functions for different sorting types (numeric, string, date, etc). You can then use this trait not only in your product class (as given in the example), but also in other classes that need similar strategies (to apply a numeric sort to some data, etc).

<?php
trait SortStrategy {
    private
$sort_field = null;
    private function
string_asc($item1, $item2) {
        return
strnatcmp($item1[$this->sort_field], $item2[$this->sort_field]);
    }
    private function
string_desc($item1, $item2) {
        return
strnatcmp($item2[$this->sort_field], $item1[$this->sort_field]);
    }
    private function
num_asc($item1, $item2) {
        if (
$item1[$this->sort_field] == $item2[$this->sort_field]) return 0;
        return (
$item1[$this->sort_field] < $item2[$this->sort_field] ? -1 : 1 );
    }
    private function
num_desc($item1, $item2) {
        if (
$item1[$this->sort_field] == $item2[$this->sort_field]) return 0;
        return (
$item1[$this->sort_field] > $item2[$this->sort_field] ? -1 : 1 );
    }
    private function
date_asc($item1, $item2) {
       
$date1 = intval(str_replace('-', '', $item1[$this->sort_field]));
       
$date2 = intval(str_replace('-', '', $item2[$this->sort_field]));
        if (
$date1 == $date2) return 0;
        return (
$date1 < $date2 ? -1 : 1 );
    }
    private function
date_desc($item1, $item2) {
       
$date1 = intval(str_replace('-', '', $item1[$this->sort_field]));
       
$date2 = intval(str_replace('-', '', $item2[$this->sort_field]));
        if (
$date1 == $date2) return 0;
        return (
$date1 > $date2 ? -1 : 1 );
    }
}

class
Product {
    public
$data = array();
   
    use
SortStrategy;
   
    public function
get() {
       
// do something to get the data, for this ex. I just included an array
       
$this->data = array(
           
101222 => array('label' => 'Awesome product', 'price' => 10.50, 'date_added' => '2012-02-01'),
           
101232 => array('label' => 'Not so awesome product', 'price' => 5.20, 'date_added' => '2012-03-20'),
           
101241 => array('label' => 'Pretty neat product', 'price' => 9.65, 'date_added' => '2012-04-15'),
           
101256 => array('label' => 'Freakishly cool product', 'price' => 12.55, 'date_added' => '2012-01-11'),
           
101219 => array('label' => 'Meh product', 'price' => 3.69, 'date_added' => '2012-06-11'),
        );
    }
   
    public function
sort_by($by = 'price', $type = 'asc') {
        if (!
preg_match('/^(asc|desc)$/', $type)) $type = 'asc';
        switch (
$by) {
            case
'name':
               
$this->sort_field = 'label';
               
uasort($this->data, array('Product', 'string_'.$type));
            break;
            case
'date':
               
$this->sort_field = 'date_added';
               
uasort($this->data, array('Product', 'date_'.$type));
            break;
            default:
               
$this->sort_field = 'price';
               
uasort($this->data, array('Product', 'num_'.$type));
        }
    }
}

$product = new Product();
$product->get();
$product->sort_by('name');
echo
'<pre>'.print_r($product->data, true).'</pre>';
?>
up
9
ryanhanekamp at yahoo dot com
7 years ago
Using AS on a __construct method (and maybe other magic methods) is really, really bad. The problem is that is doesn't throw any errors, at least in 5.4.0. It just sporadically resets the connection. And when I say "sporadically," I mean that arbitrary changes in the preceding code can cause the browser connection to reset or not reset *consistently*, so that subsequent page refreshes will continue to hang, crash, or display perfectly in the same fashion as the first load of the page after a change in the preceding code, but the slightest change in the code can change this state. (I believe it is related to precise memory usage.)

I've spent a good part of the day chasing down this one, and weeping every time commenting or even moving a completely arbitrary section of code would cause the connection to reset. It was just by luck that I decided to comment the

"__construct as primitiveObjectConstruct"

line and then the crashes went away entirely.

My parent trait constructor was very simple, so my fix this time was to copy the functionality into the child __construct. I'm not sure how I'll approach a more complicated parent trait constructor.
up
1
katrinaelaine6 at gmail dot com
2 years ago
Adding to "atorich at gmail dot com":

The behavior of the magic constant __CLASS__ when used in traits is as expected if you understand traits and late static binding (http://php.net/manual/en/language.oop5.late-static-bindings.php).

<?php

$format
= 'Class: %-13s | get_class(): %-13s | get_called_class(): %-13s%s';

trait
TestTrait {
    public function
testMethod() {
        global
$format;
       
printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
   
    public static function
testStatic() {
        global
$format;
       
printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
}

trait
DuplicateTrait {
    public function
duplMethod() {
        global
$format;
       
printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
   
    public static function
duplStatic() {
        global
$format;
       
printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
}

abstract class
AbstractClass {
   
    use
DuplicateTrait;
   
    public function
absMethod() {
        global
$format;
       
printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
   
    public static function
absStatic() {
        global
$format;
       
printf($format, __CLASS__, get_class(), get_called_class(), PHP_EOL);
    }
}

class
BaseClass extends AbstractClass {
    use
TestTrait;
}

class
TestClass extends BaseClass { }

$t = new TestClass();

$t->testMethod();
TestClass::testStatic();

$t->absMethod();
TestClass::absStatic();

$t->duplMethod();
TestClass::duplStatic();

?>

Will output:

Class: BaseClass     | get_class(): BaseClass     | get_called_class(): TestClass   
Class: BaseClass     | get_class(): BaseClass     | get_called_class(): TestClass   
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass   
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass   
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass   
Class: AbstractClass | get_class(): AbstractClass | get_called_class(): TestClass

Since Traits are considered literal "copying/pasting" of code, it's clear how the methods defined in DuplicateTrait give the same results as the methods defined in AbstractClass.
up
5
Anonymous
1 year ago
", но нельзя определить статические переменные в самом трейте." - зачем вводите людей в заблуждение?

Документация помечена как ооп5 (я не знаю с какой версии есть такая возможность, до сего дня верил вам и думал что нельзя), но учитывая что здесь и по более поздним версиям информация, то Вы как то пометьте что статические переменные могут быть в трейте не только в методах трейта, но и сами по себе свойствами трейта.
up
8
ryan dot yoosefi at gmail dot com
5 years ago
Visibility in traits is not shared between trait users.

<?php

trait T {
    protected
$secret = 1;
}

class
X {
    use
T;
    public function
peek ( Y $y ) {
        echo
$y->secret;
    }
}

class
Y {
    use
T;
}

(new
X)->peek(new Y); // Fatal:  Cannot access protected property Y::$secret
?>

This is as expected when thinking of traits as language assisted copy-paste.
up
3
84td84 at gmail dot com
4 years ago
A note to 'Beispiel #9 Statische Variablen'. A trait can also have a static property:

trait Counter {
    static $trvar=1;

    public static function stfunc() {
        echo "Hello world!"
    }
}

class C1 {
    use Counter;
}

print "\nTRVAR: " . C1::$trvar . "\n";   //prints 1

$obj = new C1();
C1::stfunc();   //prints  Hello world!
$obj->stfunc();   //prints Hello world!

A static property (trvar) can only be accessed using the classname (C1).
But a static function (stfunc) can be accessed using the classname or the instance ($obj).
up
1
bscheshirwork at gmail dot com
2 years ago
https://3v4l.org/mFuQE

1. no deprecate if same-class-named method get from trait
2. replace same-named method ba to aa in C

trait ATrait {
    public function a(){
        return 'Aa';
    }
}

trait BTrait {
    public function a(){
        return 'Ba';
    }
}

class C {
    use ATrait{
        a as aa;
    }
    use BTrait{
        a as ba;
    }
   
    public function a() {
        return static::aa() . static::ba();
    }
}

$o = new C;
echo $o->a(), "\n";

class D {
    use ATrait{
        ATrait::a as aa;
    }
    use BTrait{
        BTrait::a as ba;
    }
   
    public function a() {
        return static::aa() . static::ba();
    }
}

$o = new D;
echo $o->a(), "\n";

class E {
    use ATrait{
        ATrait::a as aa;
        ATrait::a insteadof BTrait;
    }
    use BTrait{
        BTrait::a as ba;
    }
   
    public function e() {
        return static::aa() . static::ba();
    }
}

$o = new E;
echo $o->e(), "\n";

class F {
    use ATrait{
        a as aa;
    }
    use BTrait{
        a as ba;
    }
   
    public function f() {
        return static::aa() . static::ba();
    }
}

$o = new F;
echo $o->f(), "\n";

AaAa
AaBa

Deprecated: Methods with the same name as their class will not be constructors in a future version of PHP; E has a deprecated constructor in /in/mFuQE on line 48
AaBa

Fatal error: Trait method a has not been applied, because there are collisions with other trait methods on F in /in/mFuQE on line 65
up
3
Oddant
6 years ago
I think it's obvious to notice that using 'use' followed by the traits name must be seen as just copying/pasting lines of code into the place where they are used.
up
1
Carlos Alberto Bertholdo Carucce
3 years ago
If you want to resolve name conflicts and also change the visibility of a trait method, you'll need to declare both in the same line:

trait testTrait{
   
    public function test(){
        echo 'trait test';
    }
   
}

class myClass{
   
    use testTrait {
        testTrait::test as private testTraitF;
    }
   
    public function test(){
        echo 'class test';
        echo '<br/>';
        $this->testTraitF();
    }
   
}

$obj = new myClass();
$obj->test(); //prints both 'trait test' and 'class test'
$obj->testTraitF(); //The method is not accessible (Fatal error: Call to private method myClass::testTraitF() )
up
1
vijit at mail dot ru
4 years ago
Example #9 "Static Variables" is useless. Variable $c in function will be static anyway, this is provided by scope of function. And the result will be the same without directive "static".
up
1
aram dot petrosyan dot 88 at gmail dot com
4 years ago
It's possible to define abstract function in a trait as static and implement non-static version of the function , and it will works. Like this

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

class traitTest
{
    use B;

    public static function talk()
    {
        echo 111;
    }
}

Also, it's possible to define abstract non static , and implement static version.

Can't understand , is this a bug or it's a feature :)
up
2
artur at webprojektant dot pl
7 years ago
Trait can not have the same name as class because it will  show: Fatal error: Cannot redeclare class
up
0
gulaschsuppe2 at gmail dot com
5 months ago
Like shown in other examples it is possible to define a constructors and destructors in traits:

<? php
    trait T {
        public $prop = null;

        public function __construct($prop) {
            echo "Constructor called\n";
            $this->prop = $prop;
        }

        public function __destruct() {
            echo "Destructor called\n";
        }
    }

    class A {
        use T;
    }

    $a = new A("Hello World\n"); // Constructor called
   
    echo $a->prop; // Hello World

    // Destructor called

?>

It is also possible to use trait methods as constructor/destructor using them with the alias '__construct'/'__destruct':

<?php
   
trait T {
        public
$prop = null;

        public function
constructor($prop) {
            echo
"Constructor called\n";
           
$this->prop = $prop;
        }

        public function
destructor() {
            echo
"Destructor called\n";
        }
    }

    class
A {
        use
T {
           
T::constructor as __construct;
           
T::destructor as __destruct;
        }
    }

   
$a = new A("Hello World\n"); // Constructor called
   
   
echo $a->prop; // Hello World

    // Destructor called   

?>
up
0
nobody
11 months ago
<?php
trait MyTrait {
    public function
sayHello() {
        echo
'Hello World! from MyTrait';
    }
}

class
MyClass1 {
    use
MyTrait;

    public function
sayHello() {
        echo
'Hello World from MyClasss!';
    }
}
$obj=new MyClass1();
$obj->sayHello(); //Hello World from MyClasss!⏎

?>
up
-1
Nanhe Kumar
4 years ago
<?php

//Precedence Order Example with base class
trait T {

    public function
foo() {
        echo
"T";
    }

}

class
A {

    public function
foo() {
        echo
"A";
    }

}

class
B extends A {

    use
T;
}

$o = new B();
$o->foo(); //Prints : T
?>
up
-2
lito at eordes dot com
3 years ago
trait static methods can be called without need to implement into a main class.

<?php
trait Vehicle {
    public static function
wheels() {
        return
4;
    }
}

var_dump(Vehicle::wheels()); // 4
?>

but you can not instantiate a trait:

<?php
trait Vehicle {
    public function
wheels() {
        return
4;
    }
}

var_dump((new Vehicle)->wheels()); // Fatal error: Cannot instantiate trait Vehicle
?>

For me, it's strange.
up
-3
angel dot ayora at gmail dot com
5 years ago
The traits can be used if are inherited from a parent class, but the trait still belong to parent class:

<?php

trait Singleton
{
    private static
$instance = null;

    public static function
singleton()
    {
        if(
self::$instance == null )
        {
           
self::$instance = new self();
        }
        return
self::$instance;
    }
}

class
A
{
    use
Singleton;
    private function
__construct(){}
}

class
B extends A
{
    private function
__construct(){}
}

$b = B::singleton();
echo
get_class($b); //Output: A

?>
up
-5
contato at williamsantana dot com dot br
6 years ago
Please note that a trait cannot extend a class. Traits can only contain another traits by using 'use' keyword. Things like

<?php
   
trait DetailedException extends Exception {}
?>

will not work. Be careful.

Cheers.
up
-7
bagermen at gmail dot com
3 years ago
Traits effectively replaced by OOP patterns: DI and Decorator.

Traits broke OOP.
Exapmle: Let we have an object with one method. Creator of the class used traits to overload that method.
We write client code. So there is no way to know what this object do with that method because the same class with different traits in it will do different things.

It's evident that traits are evil in your code try to use OOP instead of them
up
-5
tomasz at marcinkowski dot pl
5 years ago
Unlike the __CLASS__ constant, which returns name of a class implementing a trait, the __METHOD__ constant returns the trait method name. You might find it useful.

Example:

<?php

namespace XXX;

trait
Ta {
  public function
test1() {
    return
sprintf('class: %s, method: %s, trait: %s', __CLASS__, __METHOD__, __TRAIT__);
  }
}

class
A {
  use
Ta;
}

$a = new A();
var_dump($a->test1()); // class: XXX\A, method: XXX\Ta::test1, trait: XXX\Ta

?>
up
-15
Serafim
6 years ago
Another useful property of traits:
<?php
namespace Traits;
trait
Properties{
    public function
__get($var){
       
$var = '_' . $var;
       
$getter = '_get' . $var;
       
        if(
method_exists($this, $getter)){
            try{
               
$val = $this->$getter();
            }catch(\
Exception $e){
                throw new \
Exception($e);
            }
            return
$val;
        }
        throw new \
Exception('Can not get property: ' . $var . ', method ' . $getter . ' not exists');
    }
   
    public function
__set($var, $val){
       
$var = '_' . $var;
       
$setter = '_set' . $var;
       
        if(
method_exists($this->$setter) && isset($this->$var)){
            try{
               
$setval = $this->$setter($val);
            }catch(\
Exception $e){
                throw new \
Exception($e);
            }
           
$this->$var = ($setval === NULL) ? $this->$var : $setval;
        }else{
            throw new \
Exception('Can not set property: ' . $var . ', method ' . $setter . ' not exists');
        }
    }
}

class
Some{
  use \
Chidori\Traits\Properties;
 
 
// Magic begin
 
protected $_var = 42;
  protected function
_get_var(){ return $this->_var; }
  protected function
_set_var($val){ return NULL; }
}

$s = new Some();
$s->var = 23; \\ set value
echo $s->var; \\ return 42? where is my 23? =)
?>
up
-19
heli
4 years ago
class first_class
   {
     // Using the Trait Here
     use first_trait;
   }

   $obj = new first_class();

   // Executing the method from trait
   $obj->first_method(); // valid
   $obj->second_method(); // valid
To Top