トレイトは、継承によって関連していない複数のクラス間でコードを再利用するメカニズムです。PHPは単一継承のみを許可しているため、トレイトはメソッド(とプロパティ)を水平的に共有する方法を提供します。これはmixinのような「合成的な」コード再利用の形式です。
トレイトが解決する問題
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.
トレイトの定義と使用
{
?DateTime = ;
{
->createdAt = ();
}
{
->createdAt;
}
}
{
{
. :: . ;
}
}
{
, ;
}
= ();
->();
->();
