php实现多继承-trait语法

本文介绍了PHP 5.4.0引入的Traits特性,一种用于代码复用的机制,特别适用于单继承语言。Traits允许开发者在不同的类层次结构中复用方法,从而避免了传统多继承带来的复杂性。

自 PHP 5.4.0 起,PHP 实现了一种代码复用的方法,称为 trait。

Trait 是为类似 PHP 的单继承语言而准备的一种代码复用机制。Trait 为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一种减少复杂性的方式,避免传统多继承和 Mixin 类相关典型问题。

Trait 和 Class 相似,但仅仅旨在用细粒度和一致的方式来组合功能。 无法通过 trait 自身来实例化。它为传统继承增加了水平特性的组合;也就是说,应用的几个 Class 之间不需要继承。

从基类继承的成员会被 trait 插入的成员所覆盖。优先顺序是来自当前类的成员覆盖了 trait 的方法,而 trait 则覆盖了被继承的方法。

以下为代码:

trait traitTestOne{
    public function test(){
        echo "This is trait one ";
    }
    public function testOne(){
        echo "one ";
    }
}
 
trait traitTestTwo{
//  public function test(){
//      echo "This is trait two";
//  }
    public function testTwo(){
        echo "two ";
    }
}
 
class basicTest{
    public function test(){
        echo "hello world\n";
    }
}
class myCode extends basicTest{
    use traitTestOne,traitTestTwo;
}
 
$test = new mycode();
$test->test();
$test->testOne();
$test->testTwo();

下面是输出:

This is trait one
one
two

注意。如果把注释一行的注释取消,将会报错

Fatal error: Trait method test has not been applied, because there are collisions with other trait methods on myCode in ……test.php on line 28

是致命错误。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值