LoginSignup
1
0

More than 1 year has passed since last update.

PHP Interface

Last updated at Posted at 2022-03-14

オブジェクト インターフェイス

メソッドの実装を定義せずに、クラスが実装する必要があるメソッドを指定する。

通常のクラスと同様に定義できるがclassではなくinterfaceを用いる。

interface HogeRepository
{
  public function create(): Hoge;
  public function delete(int $id): bool;
}

役割

  • 同じインターフェイスを実装していることで、開発者が交換可能な異なるクラスを作成できる。
    実装が異なっていても、インターフェイスを使うコードに変更を加えることなく、実装を交換することができる。
  • メソッドがインターフェイスを満たす引数を受け付け、操作できるようにする。
    中身が何をするのかや、どう実装されているかを気にする必要がない

implements(実装)

インターフェイスを実装するクラスに宣言する。

class HogeProvider implements HogeRepository
{
  public function create(): Hoge
  {
    // 作成処理
    return new Hoge();
  }

  public function delete(int $id): bool
  {
    // 削除処理
    return true;
  }
}

参考

PHP オブジェクトインスタンス

1
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
1
0