php实现多继承-trait语法

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

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

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

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

以下为代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
trait traitTestOne{
    public function test(){
        echo "This is trait one <br/>";
    }
    public function testOne(){
        echo "one <br/>";
    }
}
 
trait traitTestTwo{
//  public function test(){
//      echo "This is trait two";
//  }
    public function testTwo(){
        echo "two <br/>";
    }
}
 
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();

  输出为:

1
2
3
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

是致命错误。

 

posted @   DDDDemo  阅读(7354)  评论(0编辑  收藏  举报
编辑推荐:
· 开发中对象命名的一点思考
· .NET Core内存结构体系(Windows环境)底层原理浅谈
· C# 深度学习:对抗生成网络(GAN)训练头像生成模型
· .NET 适配 HarmonyOS 进展
· .NET 进程 stackoverflow异常后,还可以接收 TCP 连接请求吗?
阅读排行:
· 本地部署 DeepSeek:小白也能轻松搞定!
· 基于DeepSeek R1 满血版大模型的个人知识库,回答都源自对你专属文件的深度学习。
· 在缓慢中沉淀,在挑战中重生!2024个人总结!
· 大人,时代变了! 赶快把自有业务的本地AI“模型”训练起来!
· Tinyfox 简易教程-1:Hello World!
点击右上角即可分享
微信分享提示