Menu
CoddyTech

인터페이스는 명목적이다

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

Rust 트레이트 구현은 동작 계약을 선언하며, 제네릭 또는 dyn 트레이트 객체가 디스패치 방식을 선택합니다. PHP 인터페이스는 명시적인 implements 선언과 호환되는 public 메서드를 요구합니다. 메서드 이름만 일치한다고 해서 명목상 소속 관계가 성립하는 것은 아니며, PHP의 제네릭 및 수명 기능은 Rust와 다릅니다.

인터페이스는 계약을 나타냅니다. 클래스는 implements를 명시적으로 선언해야 하며, 일치하는 이름의 메서드를 갖고 있다는 것만으로 해당 인터페이스의 인스턴스가 되지는 않습니다. 클래스는 여러 인터페이스를 구현할 수 있습니다. 인터페이스는 public 동작을 설명하고, 구현과 상태는 클래스에 있습니다. 독립 구현체를 사용해 소비자를 테스트하세요.

Rust 프로그램

trait Channel{fn send(&self,text:&str)->String;}
struct Email; impl Channel for Email{fn send(&self,text:&str)->String{format!("email:{}",text)}}
struct Sms; impl Channel for Sms{fn send(&self,text:&str)->String{format!("sms:{}",text)}}
fn main() {
let email=Email; let sms=Sms; let channels:[&dyn Channel;2]=[&email,&sms]; let out:Vec<_>=channels.iter().map(|c|c.send("hi")).collect(); println!("{}",out.join("|"));
}

출력 결과:

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의 수수료를 사용하며, 값은 음수가 아닙니다.

제공된 main 스크립트는 표준 입력에서 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실력 점검

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

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

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