Menu
Coddy logo textTech

인터페이스 구현

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

이제 interface가 무엇인지 이해했으니, 실제로 interface를 어떻게 구현하는지 살펴보겠습니다. 클래스는 implements 키워드를 사용하여 interface를 구현하며, 해당 interface에 선언된 모든 method에 대한 구체적인 구현을 제공해야 합니다.

<?php
interface Printable {
    public function print();
}

class Document implements Printable {
    private $content;
    
    public function __construct($content) {
        $this->content = $content;
    }
    
    public function print() {
        return "Printing: " . $this->content;
    }
}

$doc = new Document("Hello World");
echo $doc->print();

출력:

Printing: Hello World

Document 클래스는 자체적인 print() 메서드를 제공하여 Printable을 구현합니다. 필수 메서드를 구현하는 것을 잊으면 PHP에서 치명적인 오류가 발생합니다.

서로 다른 클래스는 동일한 인터페이스를 각자의 방식으로 구현할 수 있습니다:

<?php
class Invoice implements Printable {
    private $amount;
    
    public function __construct($amount) {
        $this->amount = $amount;
    }
    
    public function print() {
        return "Invoice Total: $" . $this->amount;
    }
}

$invoice = new Invoice(150);
echo $invoice->print();

출력:

Invoice Total: $150

DocumentInvoice 모두 Printable 계약을 충족하지만, 각각 목적에 따라 인쇄를 다르게 처리합니다.

핵심 요점: implements를 사용하여 클래스를 인터페이스에 연결한 다음, 필요한 모든 메서드를 정의하세요. 각 구현 클래스는 동일한 메서드 시그니처가 존재하도록 보장하면서 자체 로직을 제공합니다.

challenge icon

챌린지

쉬움

서로 다른 class가 동일한 interface를 각자의 고유한 방식으로 구현하는 방법을 보여 주는 메시징 시스템을 만들어 봅시다.

서로 다른 유형의 메시지를 처리하기 위해 함께 작동하는 세 개의 파일을 만들 것입니다:

  • Messageable.php: 두 개의 method 시그니처인 compose($content)deliver()를 포함하는 Messageable interface를 Define합니다. 이 interface는 모든 메시지 유형이 따라야 하는 계약을 설정합니다.
  • Email.php: Messageable을 implements하는 Email class를 Create합니다. 파일 상단에 interface 파일을 포함합니다. 이 class에는 private $recipient property와 private $body property가 있어야 합니다. constructor는 수신자 address를 accepts합니다. compose($content)를 Implement하여 content를 $body에 저장하고 "Email composed"를 반환합니다. deliver()를 Implement하여 "Email to [recipient]: [body]"를 반환합니다.
  • SMS.php: 역시 Messageable을 implements하는 SMS class를 Create합니다. 파일 상단에 interface 파일을 포함합니다. 이 class에는 private $phoneNumber property와 private $text property가 있어야 합니다. constructor는 phone number를 accepts합니다. compose($content)를 Implement하여 content를 $text에 저장하고 "SMS composed"를 반환합니다. deliver()를 Implement하여 "SMS to [phoneNumber]: [text]"를 반환합니다.

main.php에서 Email 및 SMS 파일을 모두 포함합니다. 세 가지 inputs, 즉 email address, phone number, message content를 받습니다. email address로 Email object를, phone number로 SMS object를 Create합니다. 두 objects 모두에서 message content와 함께 compose()를 Call하고, 각 결과를 별도의 줄에 print합니다. 그런 다음 두 objects에서 deliver()를 Call하고, 각 결과를 별도의 줄에 print합니다. 순서는 email compose, SMS compose, email deliver, SMS deliver여야 합니다.

두 class는 모두 동일한 Messageable 계약을 충족하지만, 각각 고유한 목적에 따라 메시지를 compose하고 deliver합니다. email은 수신자 address를 표시하고 SMS 메시지는 phone number를 표시합니다.

직접 해보기

<?php
require_once 'Email.php';
require_once 'SMS.php';

// 입력 읽기
$emailAddress = trim(fgets(STDIN));
$phoneNumber = trim(fgets(STDIN));
$messageContent = trim(fgets(STDIN));

// TODO: 이메일 주소로 Email 객체 생성

// TODO: 전화번호로 SMS 객체 생성

// TODO: 두 객체에서 compose()를 호출하고 결과 출력
// Order: email compose, then SMS compose

// TODO: 두 객체에서 deliver()를 호출하고 결과 출력
// 순서: email deliver, 그다음 SMS deliver
?>
quiz icon실력 점검

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

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

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