Kintarou'sBlog

プログラミング学習中。学習内容のアウトプットや読書で学んだことなど随時投稿!

【PHP】クラスの継承

こんにちは😊Kintarouです。

現在エンジニア転職を目指してプログラミング学習中です👨‍🎓
夢はフリーランスエンジニアになって働く人にとって働く事が楽しくなるシステムを作ること!
と、愛する妻と海外移住すること🗽

プログラミングや読んでいる本のことなど、ブログに書いていきます!
twitter : https://twitter.com/ryosuke_angry


今回参考にさせて頂いたサイト様🙇‍♂️ dotinstall.com


クラスを継承する

クラスを継承した子クラスを作る事が出来ます。
仮にnameプロパティを持つUserクラスがあったとして、テスト運用のためのTestUserを作るとしましょう。

<?php

#まずは親クラスとなるUserクラスです。nameプロパティを持っています。
class User
{
  private $name;

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

  public function profile()
  {
    printf('%s' . PHP_EOL, $this->name
    );
  }
}

#TestUserという、Userクラスを親にもつ子クラスを作ります。  
#extendsがUserクラスを受け継いでいる事を意味しています。
class TestUser extends User
{

}

#TestUserのインスタンスを生成します。
$users = [];
$users[0] = new TestUser('Testarou');

#TestUserには何も記述していませんが、Userクラスを継承しているのでprofileメソッドも使えます。
$users[0]->profile();
#=>Testarou

子クラス独自のプロパティとメソッドを記述する

上記のTestUserに独自のプロパティやメソッドを記述します。
どのパターンのテストをするのかを識別するpatternプロパティとパターンを表示するpatternShowメソッドを記述します。

<?php

class User
{
  private $name;

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

  public function profile()
  {
    printf('%s' . PHP_EOL, $this->name
    );
  }
}

class TestUser extends User
{
  #$patternプロパティを記述します。
  private $pattern;

  #コンストラクタにて、$nameは親クラスのプロパティなのでparent::__constructで記述します。
  public function __construct($name, $pattern)
  {
    parent::__construct($name);
    $this->pattern = $pattern;
  }

  #patternShowで$patternの内容を出力するメソッドを定義します。
  public function patternShow()
  {
    printf('%s' . PHP_EOL, $this->pattern);
  }
}

$users = [];
$users[0] = new TestUser('Testarou', 'first-pattern');

$users[0]->patternShow();
#=>first-pattern

親クラスのメソッドを再定義する

先ほどのpatternShowメソッドですが、TestUserのインスタンスの場合親クラスのprofileメソッドで$nameと一緒に出力した方が、メソッドもまとめられて便利そうです。
そうしたい場合にメソッドのオーバーライド(override)というのが使えます。

<?php

class User
{
  #子クラスでも使えるようにするためアクセス修飾子をprotectedにします。
  protected $name;

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

  public function profile()
  {
    printf('%s' . PHP_EOL, $this->name
    );
  }
}

class TestUser extends User
{
  private $pattern;

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

  #nameも追加した同名(profile)メソッドをoverrideします。
  #nameプロパティも$this->nameで記述します。
  public function profile()
  {
    printf('%s(%s)' . PHP_EOL, $this->name, $this->pattern);
  }
}

$users = [];
$users[0] = new TestUser('Testarou', 'first-pattern');

#profileメソッドで$patternも出力されています。
$users[0]->profile();
#=>Testarou(first-pattern)

※仮に継承後の子クラスでoverrideして欲しくないとなった場合には、メソッドのアクセス修飾子の前にfinalを付けるとその後のoverrideを制限できます。

以上、どなたかの参考になれば幸いです😊