class Notifier {
public function send() {
echo "通知を送信しました\n";
}
}
class EmailNotifier extends Notifier {
public function send() {
echo "メールで通知を送信しました\n"; // 上書き
}
}
<?php
class Notifier {
public function send(string $message) {
echo "通知: {$message}\n";
}
}
class EmailNotifier extends Notifier {
}
$n = new EmailNotifier();
$n->send("登録完了しました"); // 「通知: 登録完了しました」 が出る
でも Email なら メール本文 として、Slack なら チャンネル投稿 として送りたい
子クラスごとに送信処理を変えたい
子クラスで同じ名前のメソッドを書く
<?php
class Notifier {
public function send(string $message) {
echo "通知: {$message}\n";
}
}
class EmailNotifier extends Notifier {
public function send(string $message) {
echo "[Email] 件名/本文として送信: {$message}\n";
}
}
子クラスで親と 同じシグネチャ のメソッドを定義
これを オーバーライド と呼ぶ
子のインスタンスでは子のメソッドが呼ばれる
<?php
$n = new EmailNotifier();
$n->send("登録完了しました");
<?php
class Notifier {
public function send(string $message) {
echo "通知: {$message}\n";
}
}
class EmailNotifier extends Notifier {
}
$n = new EmailNotifier();
$n->send("登録完了しました"); // 「通知: 登録完了しました」 が出る
でも Email なら メール本文 として、Slack なら チャンネル投稿 として送りたい
子クラスごとに送信処理を変えたい
子クラスで同じ名前のメソッドを書く
<?php
class Notifier {
public function send(string $message) {
echo "通知: {$message}\n";
}
}
class EmailNotifier extends Notifier {
public function send(string $message) {
echo "[Email] 件名/本文として送信: {$message}\n";
}
}
子クラスで親と 同じシグネチャ のメソッドを定義
これを オーバーライド と呼ぶ
子のインスタンスでは子のメソッドが呼ばれる
<?php
$n = new EmailNotifier();
$n->send("登録完了しました");