0
0

トレイト

Posted at

はじめに

トレイトについてまとめる

トレイトとは

いくつかのメソッド群を独立したクラスで再利用できるようにした仕組みのこと。
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クラスを定義している。
また、トレイトは実装を表すだけで型を定義できないため、インターフェイスを定義している。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0