0
0

オーバーライド

Last updated at Posted at 2024-05-03

はじめに

継承についてまとめる・二回目

オーバーライドとは

スーパークラスで定義された機能を他のクラスで再定義すること。

参考コード

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(); // 私の名前は佐藤次郎です

PersonBusinessPersonEliteBusinessPerson
の順で継承している

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(); // 私の名前は鈴木ヨーダ太郎です
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