PHP trait特性

trait 特点、特征、特性

1 为什么设计trait

因为PHP是单继承的,php 5.4.0设计trait就是为了解决单继承和代码复用问题

2 如何使用

trait不能实例化,只需在类中使用use + trait名称,多个用逗号隔开

trait T{
    public function f(){
        echo "T";
    }
}

class C{
    use T;
}

$c = new C();
$c->f();
3 属性与方法

优先顺序是当前类中的方法会覆盖 trait 方法,而 trait 方法又覆盖了基类中的方法。

trait属性和类的属性不能重复,否则报fatal error,当然你可以在子类中重写trait中的初始化属性方法。

多个trait的方法冲突时,只是在use时声明方法属于哪个trait,需要insteadof处理一下,也可以用as重命名方法如下:

trait A {
    public function smallWord() {
        echo 'a';
    }
    public function bigWord() {
        echo 'A';
    }
}

trait B {
    public function smallWord() {
        echo 'b';
    }
    public function bigWord() {
        echo 'B';
    }
}

class Writer {
    use A, B {
        B::smallWord insteadof A;  //指定使用B的smallWord()
        A::bigWord insteadof B;  //指定使用A的bigWord()
        B::bigWord as word;  //给B的smallWord()指定别名
    }
}
4 多个trait组合
trait Hello {
    public function sayHello() {
        echo 'Hello ';
    }
}

trait World {
    public function sayWorld() {
        echo 'World!';
    }
}

trait HelloWorld {
    use Hello, World;
}
5 理解trait

The best way to understand what traits are and how to use them is to look at them for what they essentially are: language assisted copy and paste.

If you can copy and paste the code from one class to another (and we’ve all done this, even though we try not to because its code duplication) then you have a candidate for a trait.

6 关于__class__

CLASS will return the name of the class in which the trait is being used (!) not the class in which trait method is being called:

7 trait and inheritance

trait是组合,临时打破单继承

Another difference with traits vs inheritance is that methods defined in traits can access methods and properties of the class they’re used in, including private ones.

参考文档
1 https://www.php.net/manual/zh/language.oop5.traits.php
2 https://www.php.net/manual/en/language.oop5.traits.php

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值