Menu
Coddy logo textTech

다중 인터페이스 구현

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

클래스가 하나의 부모만 확장할 수 있는 상속과 달리, PHP에서는 클래스가 여러 인터페이스를 Implement할 수 있습니다. 이를 통해 서로 다른 계약을 결합할 수 있는 유연성이 생기며, 클래스를 더욱 다용도로 만들 수 있습니다.

여러 인터페이스를 구현하려면 implements 키워드 뒤에서 인터페이스를 쉼표로 구분하세요:

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

interface Savable {
    public function save();
}

class Report implements Printable, Savable {
    private $title;
    
    public function __construct($title) {
        $this->title = $title;
    }
    
    public function print() {
        return "Printing: " . $this->title;
    }
    
    public function save() {
        return "Saving: " . $this->title;
    }
}

$report = new Report("Sales Report");
echo $report->print() . "\n";
echo $report->save();

출력:

Printing: Sales Report
Saving: Sales Report

Report 클래스는 PrintableSavable의 모든 methods를 Implement하여 두 계약을 모두 충족합니다. 각 interface에서 선언된 모든 method에 대한 구현을 제공해야 합니다.

이 접근 방식은 단일 상속의 제약 없이 여러 요구 사항을 충족하는 클래스를 만들 수 있게 해 주므로 강력합니다. 클래스는 printable, 저장 가능, exportable 등 여러 기능을 동시에 수행할 수 있습니다.

핵심 요점: 여러 interfaces를 구현하려면 쉼표를 사용하세요. class는 구현하는 모든 interface의 모든 methods에 대해 구체적인 구현을 제공해야 합니다.

challenge icon

챌린지

쉬움

서로 다른 기능을 얻기 위해 하나의 class가 여러 interface를 implements할 수 있는 방법을 보여 주는 미디어 file system을 만들어 보겠습니다.

함께 작동하여 재생과 공유가 모두 가능한 미디어 files를 처리하는 네 개의 files를 Create합니다:

  • Playable.php: 하나의 method signature인 play()를 포함하는 Playable interface를 Define합니다. 이 contract는 재생 가능한 미디어를 시작할 수 있도록 보장합니다.
  • Shareable.php: 하나의 method signature인 share($platform)를 포함하는 Shareable interface를 Define합니다. 이 contract는 공유 가능한 콘텐츠를 서로 다른 platform에 배포할 수 있도록 보장합니다.
  • Video.php: PlayableShareable 모두를 implements하는 Video class를 Create합니다. 두 interface file을 상단에 Include합니다. class에는 private $title property와 private $duration property(분 단위)가 있어야 합니다. constructor는 title과 duration을 accepts합니다. play()를 Implement하여 "Playing video: [title] ([duration] min)"을 return합니다. share($platform)를 Implement하여 "Sharing [title] on [platform]"을 return합니다.
  • main.php: Video file을 Include합니다. 세 가지 inputs를 받습니다. video title, duration(정수로 변환할 string), 그리고 platform name입니다. title과 duration으로 Video object를 Create합니다. 첫 번째 line에는 play()를 calling한 result를 Print하고, 두 번째 line에는 platform과 함께 share()를 calling한 result를 Print합니다.

여러분의 Video class는 동시에 두 개의 서로 다른 contract를 충족합니다. 어떤 미디어처럼 play할 수 있고, social platform에 share할 수도 있습니다. 이것이 여러 interface를 Implement하는 것의 힘입니다. 하나의 class가 단일 상속 chain에 제한되지 않고 서로 다른 source에서 capabilities를 얻습니다.

직접 해보기

<?php
// Video 파일 포함
require_once 'Video.php';

// 입력 읽기
$title = trim(fgets(STDIN));
$duration = intval(trim(fgets(STDIN)));
$platform = trim(fgets(STDIN));

// TODO: title과 duration으로 Video 객체 생성

// TODO: 첫 번째 줄에 play() 호출 결과 출력

// TODO: 두 번째 줄에 platform으로 share() 호출 결과 출력

?>
quiz icon실력 점검

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

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

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