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名称。

猜你喜欢

转载自blog.csdn.net/d_x_p_m_12/article/details/80929458
今日推荐