1. 程式人生 > >PHP中trait示例

PHP中trait示例

trait Animail{
    function traitName(){
        echo __TRAIT__;
        echo "<br>";
        return $this;
    }

    function getName(){
        echo __FUNCTION__;
        return $this;
    }
}

trait Plant{
    use Animail;
}

class Test{
    use Plant;
}
echo "<pre>";
(new Test)->
traitName()->getName(); echo "<br><br>"; trait trait1{ public function eat(){ echo "This is trait1 eat"; } public function drive(){ echo "This is trait1 drive"; } } trait trait2{ public function eat(){ echo "This is trait2 eat"; }
public function drive(){ echo "This is trait2 drive"; } } class cat{ use trait1,trait2{ trait1::eat insteadof trait2; trait1::drive insteadof trait2; } } class dog{ use trait1,trait2{ trait1::eat insteadof trait2; trait1::drive insteadof trait2
; trait2::eat as eaten; trait2::drive as driven; } } $cat = new cat(); $cat->eat(); echo "<br/>"; $cat->drive(); echo "<br/>"; echo "<br/>"; echo "<br/>"; $dog = new dog(); $dog->eat(); echo "<br/>"; $dog->drive(); echo "<br/>"; $dog->eaten(); echo "<br/>"; $dog->driven();

 

執行結果:

Animail
getName

This is trait1 eat
This is trait1 drive


This is trait1 eat
This is trait1 drive
This is trait2 eat

This is trait2 drive

trait定義的類不能例項化,可以在其他類中使用use進行繼承,可以變相實現php的多類繼承。如果要使用多個trait,

如果出現衝突可以將trait中的方法使用insteadof或者取別名的as方式進行區分。預定義常量__TRAIT__可以獲取trait名稱。