PHP类的多继承的实现- trait 使用语法

166次阅读
没有评论
 性状 trait 既不是类也不是接口 是类的部分实现 (即常量, 属性和方法), 可以混入一个或多个现有的 php 类中.
性状有两个作用: 表明类可以做什么 像是接口, 提供模块化实现 像是类
 

trait A
{
    protected $a_test1=1;

    protected  $a_tets2=2;


    public function a_out(){return $this->a_test1.'+'.$this->a_tets2.'='.$this->a_test1+$this->a_tets2;}


}


trait B
{
    protected $b_test1 = 10;

    protected $b_test2 = 20;

    public function b_out()
    {return $this->b_test1.'+'.$this->b_tets2.'='.$this->b_test1+$this->b_tets2;}
}

class test
{
    use A;

    use B;
}

$t = (new test());  // 运行结果显示 3
正文完
有偿技术支持加微信
post-qrcode
 
评论(没有评论)
验证码