본문 바로가기

Develop/PHP

Trait

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


It is useful in single inheritance languages.

Trait is similar class, but only it make to group functionality.


For example, you need same functions in two absolutely different class.

At that time declare that functions as trait and use it in your class.


Like this..


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

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

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


The getRetuntType and getReturnDescription functions not declared in ReflectionMethod and each classes.

This function declare in ezcReflectionReturnInfo trait.

You can use that two functions in your different kind classes.


This Trait make your code more reuseful.


You can use multi Trait and implementation under an additional alias to conflict resolution.


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

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


And also can changing method visibility.


class MyClass1 {
    use 
HelloWorld sayHello as protected; }
}


As 7.0.0, defining a property in the class with the same visibility and initial value as in the trait, no more E_STRICT notice.

You can set properties in trait and use it and redefine in your class.