Menu
CoddyTech

인터페이스는 명목적이다

Coddy의 C 개발자를 위한 PHP 코스 레슨. 48개 중 36번째.

C는 함수 포인터 테이블과 명시적 수신자 포인터를 통해 호출 가능한 규약을 정의할 수 있습니다. PHP 인터페이스는 명목적(nominal)입니다. 클래스는 호환되는 메서드와 함께 implements를 명시적으로 선언해야 합니다. 단지 함수 이름이 일치한다는 이유만으로 인터페이스 멤버십이 성립하지는 않습니다. 동일한 공개 계약의 독립적인 구현을 테스트해보세요.

인터페이스는 계약을 정의합니다. 클래스는 implements를 명시적으로 선언해야 하며, 단순히 일치하는 이름의 메서드를 가지고 있다고 해서 해당 인터페이스의 인스턴스가 되는 것은 아닙니다. 클래스는 여러 인터페이스를 구현할 수 있습니다. 인터페이스는 공개 동작을 설명하는 반면, 구현과 상태는 클래스에 존재합니다. 독립적인 구현으로 소비자를 테스트해보세요.

C 프로그램

#include <stdio.h>
#include <stddef.h>
struct Channel {
    const char *prefix;
    void (*send)(const struct Channel *self, const char *text);
};
static void send_prefixed(const struct Channel *self, const char *text)
{
    printf("%s:%s", self->prefix, text);
}
int main(void)
{
    struct Channel channels[] = {
        {"email", send_prefixed}, {"sms", send_prefixed}
    };
    for (size_t i = 0; i < 2; ++i) {
        if (i != 0) {
            putchar('|');
        }
        channels[i].send(&channels[i], "hi");
    }
    putchar('\n');
    return 0;
}

소스 출력:

email:hi|sms:hi

PHP 프로그램

Named.php

<?php
declare(strict_types=1);
interface Named {public function name():string;}

Book.php

<?php
declare(strict_types=1);
require_once __DIR__."/Named.php";class Book implements Named {public function name():string{return "atlas";}}

demo.php

<?php
declare(strict_types=1);
require_once __DIR__."/Book.php";$b=new Book();echo ($b instanceof Named?"yes":"no"),"\n";

PHP 출력:

yes
challenge icon

챌린지

쉬움

입력은 정수 센트입니다. Fee는 apply(int $cents):int를 정의합니다. FlatFee(int $amount)는 Fee를 구현하며, apply는 금액을 더합니다. 드라이버는 3의 수수료를 사용하며, 값은 음수가 아닙니다.

제공된 메인 스크립트는 표준 입력에서 하나의 JSON 값을 읽고, 지정된 퍼블릭 API를 검사한 후 결과를 출력합니다. 출력하지 않고 모듈 선언을 구현하세요. 런처를 교체하거나 모듈에서 입력을 읽지 마세요. 입력은 명시된 타입과 범위를 충족합니다.

Fee.php, FlatFee.php를 수정하세요. main.php는 잠긴 엔트리 파일입니다. 의존성은 상대 파일 이름과 함께 require_once __DIR__를 사용합니다.

직접 해보기

<?php
declare(strict_types=1);
require_once __DIR__."/Fee.php";
require_once __DIR__."/FlatFee.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}

$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$f=new FlatFee(8);ensure($f instanceof Fee && $f->apply(4)===12,"nominal fee");
echo (string)(new FlatFee(3))->apply($input),"\n";
quiz icon실력 점검

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

C 개발자를 위한 PHP의 모든 레슨

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