はじめに
継承についてまとめる・二回目
オーバーライドとは
スーパークラスで定義された機能を他のクラスで再定義すること。
参考コード
Person.php
class Person
{
public $firstName;
public $lastName;
public function __construct($firstName, $lastName)
{
$this->firstName = $firstName;
$this->lastName = $lastName;
}
public function show()
{
print "<p>私の名前は{$this->lastName}{$this->firstName}です。</p>";
}
}
BusinessPerson.php
require_once 'Person.php';
class BusinessPerson extends Person
{
public function work(): void
{
print "<p>{$this->lastName}{$this->firstName}は働いています。</p>";
}
}
EliteBusinessPerson.php
require_once 'BusinessPerson.php';
class EliteBusinessPerson extends BusinessPerson
{
public function work(): void
{
print "<p>{$this->lastName}{$this->firstName}はバリバリ働いています。</p>";
}
}
override1.php
require_once 'EliteBusinessPerson.php';
$bp = new EliteBusinessPerson('佐藤', '次郎');
$bp->work(); // 佐藤次郎はバリバリ働いています
$bp->show(); // 私の名前は佐藤次郎です
Person
→ BusinessPerson
→ EliteBusinessPerson
の順で継承している
work
メソッドをEliteBusinessPerson
クラスで上書きしている。
show
メソッドは上書きしていないのでPerson
クラスで定義されたshow
メソッドが実行されている
parentキーワード
スーパークラスを呼び出す。
参考コード1
スーパークラスの機能を流用しつつ、サブクラス側で独自の機能を追加している
HetareBusinessPerson.php
require_once 'BusinessPerson.php';
class HetareBusinessPerson extends BusinessPerson
{
public function work(): void
{
parent::work();
print "ただしボチボチと"; // 独自の処理
}
}
override2.php
require_once 'EliteBusinessPerson.php';
$bp = new EliteBusinessPerson('鈴木', '太郎');
$bp->work(); // 鈴木太郎はバリバリ働いています。ただしボチボチと
参考コード2
スーパークラスのコンストラクターを流用しながらサブクラスのコンストラクターを定義している
Foreigner.php
requier_once 'Person.php'
class Foreigner
{
public string $middleName;
public function __construct($firstName, $middleName, $lastName)
{
parent::__construct($firstName, $lastName);
$this->middleName = $middleName;
}
public function show()
{
print "<p>私の名前は{$this->lastName}{$this->middleName}{$this->firstName}です。</p>";
}
}
override3.php
require_once 'Foreigner.php';
$bp = new Foreigner('鈴木', 'ヨーダ','太郎');
$bp->show(); // 私の名前は鈴木ヨーダ太郎です