trait 是一种在多个彼此没有继承关系的类之间复用代码的机制。由于 PHP 只允许单继承,trait 提供了一种横向共享方法(和属性)的方式 —— 一种 “组合式” 的代码复用,类似于 mixin。
trait 要解决的问题
text
PHP has single inheritance — a class can extend only ONE parent. But you often want
to share the SAME methods across unrelated classes (e.g. logging, timestamps).
Duplicating the code is bad; traits let you reuse it without inheritance.
定义和使用 trait
php
{
?DateTime = ;
{
->createdAt = ();
}
{
->createdAt;
}
}
{
{
. :: . ;
}
}
{
, ;
}
= ();
->();
->();
