0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

interface インターフェース PHP オブジェクト指向

Last updated at Posted at 2021-03-13

#interfaceとは
すでに親クラスが存在するが、すべての子クラスではなく特定のクラスにのみ継承したい場合に使用する

以下の場合、Postクラスにのみメソッドの指定を強要したい場合を考える
しかし、使用上、子クラスは一つの親クラスしか持ってはいけない

abstract class BasePost
{
  protected $text;

  public function __construct($text)
  {
    $this->text = $text;
  }

  abstract public function show();
}

class Post extends BasePost
{
  public function show()
  {
    echo $this->text . PHP_EOL;
  }
}

class StaredPost extends BasePost
{
  private $star;

  public function __construct($text, $sponsor)
  {
    parent::__construct($text);
    $this->star = $star;
  }

  public function show()
  {
    echo $this->text . PHP_EOL;
    echo $this->star . PHP_EOL;
  }
}

##使い方
①interfaceとその中に強要したいメソッドを一番上に表記する
②指定したいクラスに[implements interface名]を追記する
③指定したクラスに処理を追加する

//①
interface plusInterface
{
  public function plus();
}

abstract class BasePost
{
  protected $text;

  public function __construct($text)
  {
    $this->text = $text;
  }

  abstract public function show();
}
//②
class Post extends BasePost implements plusInterface
{
 //③
  private $pluses = 0;

  public function pluses()
  {
    $this->pluses++;
  }

  public function show()
  {
    echo $this->text . PHP_EOL;
    echo $this->pluses . PHP_EOL;
  }
}

class StaredPost extends BasePost
{
  private $star;

  public function __construct($text, $star)
  {
    parent::__construct($text);
    $this->star = $star;
  }

  public function show()
  {
    echo $this->text . PHP_EOL;
    echo $this->star . PHP_EOL;
  }
}

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?