トレイト
トレイトの基本
トレイトとは、メソッドやプロパティをまとめて切り出しておくための仕組み。「断片的なクラス」のようなもので、自分自身をインスタンス化することはできない。
<?php // トレイトを定義 trait MachineTrait { private $starting = 'Starting...Run!'; public function run() { print $this->starting; } } ?>
<?php class Fax { // トレイトをインポート use MachineTrait; public function send() { print 'Sending Fax...Sended!'; } } $fax = new Fax(); $fax->run(); // Starting...Run! ?>
traitブロックの構文はほぼclassブロックに準ずるが、以下の制約がある。
- 定数は持てない
- クラスの継承、インターフェイスの実装はできない
トレイトとインターフェイス
<?php interface IFax { function send(); } interface IPrinter { function print(); } trait FaxTrait { public function send() { print 'Sending...'; } } trait PrinterTrait { public function print() { print 'Printing...'; } } class FaxPrinter implements IFax, IPrinter { use FaxTrait, PrinterTrait; } $fax_printer = new FaxPrinter $fax_printer->send(); // 'Sending...' ?>
クラスの多重継承は禁止されているが、トレイトはクラスから複数利用することができる。
インターフェイスも同様にクラスから複数利用することができるが、インターフェイスは
- 実装を持たない型の宣言に過ぎない(内容はそれをオーバーライドするメソッドが決める)
のに対し、トレイトは
- 実装を表す(ただし型を表現できない)
という相違点がある。トレイトはインターフェイスとあわせて利用するのがお作法らしいが、インターフェイスを定義せずそのままトレイトをインポートするだけでもコードは正しく動作する。