はじめに
トレイトについてまとめる
トレイトとは
いくつかのメソッド群を独立したクラスで再利用できるようにした仕組みのこと。
PHPの継承では単一継承しかできないが、トレイトを使えば多重継承のようなことが可能。
参考コード
trait_multi.php
interface IFax {
function send();
}
interface IPrinter {
function print();
}
trait FaxTrait {
public function send() : void {
print 'sening Fax...sended!';
}
}
trait PrinterTrait {
public function print() : void {
print 'printing...completed!';
}
}
class FaxPrinter implements IFax, IPrinter {
use FaxTrait, PrinterTrait;
}
$fp = new FaxPrinter();
$fp->send(); // 結果:sending Fax...sended!
$fp->print(); // 結果:printing...completed!
FaxTrait
, PrinterTrait
双方の機能を引き継いだFaxPrinter
クラスを定義している。
また、トレイトは実装を表すだけで型を定義できないため、インターフェイスを定義している。