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

你可能感兴趣的:(PHP技术分享,php,trait,设计模式)