Menu
Coddy logo textTech

메서드 오버라이딩

Coddy PHP 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 91개 중 23번째.

때로는 부모 클래스에서 상속된 메서드가 자식 클래스에 필요한 내용과 잘 맞지 않습니다. 메서드 오버라이딩을 사용하면 자식 클래스가 부모에 이미 존재하는 메서드에 대한 자체 구현을 제공할 수 있습니다.

메서드를 재정의하려면 자식 클래스에서 부모 메서드와 같은 이름의 메서드를 정의하면 됩니다:

<?php
class Animal {
    public $name;
    
    public function __construct($name) {
        $this->name = $name;
    }
    
    public function speak() {
        return "$this->name makes a sound";
    }
}

class Cat extends Animal {
    public function speak() {
        return "$this->name says meow";
    }
}

$cat = new Cat("Whiskers");
echo $cat->speak();

출력:

Whiskers says meow

Cat class는 parent의 speak() method를 completely own 버전으로 대체합니다. cat object에서 speak()을 호출하면 PHP는 자식의 구현을 사용합니다.

parent::를 자체 로직과 결합하여 부모의 동작을 확장할 수도 있습니다.

<?php
class Dog extends Animal {
    public function speak() {
        return parent::speak() . " - woof woof!";
    }
}

$dog = new Dog("Rex");
echo $dog->speak();

출력:

Rex makes a sound - woof woof!

핵심 사항: Method overriding을 사용하면 자식 클래스가 상속된 behavior를 사용자 지정할 수 있습니다. Method를 completely replace하거나 parent::를 사용하여 원래 구현을 기반으로 확장할 수 있습니다.

challenge icon

챌린지

쉬움

method overriding을 통해 child classes가 parent methods를 완전히 replace하거나 확장할 수 있는 방식을 보여 주는 notification system을 만들어 보겠습니다.

서로 함께 작동하여 다양한 유형의 notification을 보내는 세 개의 파일을 만들게 됩니다. 각 notification은 고유한 behavior를 가집니다.

  • Notification.php: 모든 notification 유형의 기반이 되는 Notification class를 정의합니다. public $recipient property와 recipient를 accepts하고 설정하는 constructor를 포함해야 합니다. send($message) method는 "Sending to [recipient]: [message]"를 returns해야 합니다.
  • UrgentNotification.php: Notification을 extends하는 UrgentNotification class를 정의합니다. 파일 상단에 Notification 파일을 포함합니다. 이 class는 send($message) method를 완전히 Override하여 "URGENT to [recipient]: [message]!!!"를 returns해야 합니다. "URGENT" 접두사와 끝의 느낌표에 주목하세요. 이는 parent의 behavior를 완전히 replace하는 방식을 보여 줍니다.
  • LoggedNotification.php: Notification을 extends하는 LoggedNotification class를 정의합니다. 파일 상단에 Notification 파일을 포함합니다. 이 class는 send($message)를 Override하되 parent의 구현을 기반으로 동작해야 합니다. parent::send($message)를 Call하고 result에 " [logged]"를 append합니다. 이는 behavior를 replace하는 대신 확장하는 방식을 보여 줍니다.

main.php에서 세 notification class 파일을 모두 포함합니다. 두 개의 입력을 받습니다. recipient 이름과 보낼 message입니다. 각 notification 유형의 instance를 하나씩 Create하고(모두 same recipient를 사용), 각 instance에서 message와 함께 send()를 Call합니다. 각 result를 한 줄에 하나씩 다음 order로 Print합니다: regular notification, urgent notification, 그리고 logged notification.

이 challenge는 method overriding에 대한 두 가지 접근 방식을 모두 보여 줍니다. UrgentNotification은 자체 formatting으로 parent의 logic을 완전히 replace하는 반면, LoggedNotificationparent::를 사용하여 원래의 behavior를 유지하고 여기에 내용을 추가합니다.

직접 해보기

<?php

require_once 'Notification.php';
require_once 'UrgentNotification.php';
require_once 'LoggedNotification.php';

// 입력 읽기
$recipient = trim(fgets(STDIN));
$message = trim(fgets(STDIN));

// TODO: 각 알림 유형의 인스턴스를 하나씩 생성하세요 (모두 동일한 수신자 사용)

// TODO: 각 알림에 메시지로 send()를 호출하세요
// 각 결과를 다음 순서대로 한 줄에 출력하세요:
// 1. 일반 알림
// 2. 긴급 알림
// 3. 로그된 알림

?>
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 PHP 컴파일러