概述
自PHP 5.4.0 起, PHP 实现了一种代码复用的方法,称为 trait.
作用
Trait是为类似 PHP 的单继承语言而准备的一种代码复用机制。
Trait为了减少单继承语言的限制,使开发人员能够自由地在不同层次结构内独立的类中复用 method。Trait 和 Class 组合的语义定义了一个减少复杂性的方式,避免传统多继承和Mixin类相关典型问题。
以lavarel框架中的软删除需要引入的复用method
<?php
namespace Illuminate\Database\Eloquent;
trait SoftDeletes
{
/**
* Indicates if the model is currently force deleting.
*
* @var bool
*/
protected $forceDeleting = false;
/**
* Boot the soft deleting trait for a model.
*
* @return void
*/
public static function bootSoftDeletes()
{
static::addGlobalScope(new SoftDeletingScope);
}
}
优先级
优先顺序是来自基类的成员会被trait插入的成员所覆盖,当前类的成员则会覆盖trait的成员。
例:
// 创建一个基类
class Base {
public function show() {
echo "hello ";
}
}
trait New1 {
public function show()
{
parent::show(); // 调用的是使用该类的父类的show方法,这个show方法必须存在,不存在就会报错
echo "world!";
}
}
class MyTest extends Base {
// 复用了New1中的所有方法
use New1;
}
$o = new MyTest();
// 调用该类的show方法,基类中的show和New1当中,都有show, New1当中的show会覆盖掉基类的show方法
$o->show();
运行结构
hello word!