PHP中trait示例

trait Animail{
    function traitName(){
        echo __TRAIT__;
        echo "
"
; return $this; } function getName(){ echo __FUNCTION__; return $this; } } trait Plant{ use Animail; } class Test{ use Plant; } echo "
";
(new Test)->traitName()->getName();

echo "

"
; 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 "
"
; $cat->drive(); echo "
"
; echo "
"
; echo "
"
; $dog = new dog(); $dog->eat(); echo "
"
; $dog->drive(); echo "
"
; $dog->eaten(); echo "
"
; $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名称。

你可能感兴趣的:(PHP)