인터페이스는 명목적이다
Coddy의 Kotlin 개발자를 위한 PHP 코스 레슨. 48개 중 36번째.
Kotlin 인터페이스는 선언된 계약을 정의하며 기본 구현을 포함할 수 있습니다. PHP 인터페이스도 implements를 통한 명시적인 멤버십을 요구하지만, 구현 재사용은 클래스나 트레이트에서 이루어집니다. 메서드 이름만 일치한다고 해서 PHP 객체가 인터페이스를 구현하는 것은 아닙니다.
인터페이스는 계약을 정의합니다. 클래스는 implements를 명시적으로 선언해야 합니다. 메서드 이름이 일치하는 것만으로는 해당 인터페이스의 인스턴스가 되지 않습니다. 클래스는 여러 인터페이스를 구현할 수 있습니다. 인터페이스는 공개 동작을 설명하며, 구현과 상태는 클래스에 있습니다. 독립적인 구현체를 사용해 소비자를 테스트하세요.
Kotlin 프로그램
interface Channel {fun send(text:String):String}
class Email:Channel {override fun send(text:String)="email:$text"}
class Sms:Channel {override fun send(text:String)="sms:$text"}
fun main(){
val channels=listOf<Channel>(Email(),Sms())
println(channels.joinToString("|"){it.send("hi")})
}
소스 출력:
email:hi|sms:hiPHP 프로그램
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챌린지
쉬움입력은 정수 센트 단위입니다. 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";
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Kotlin 개발자를 위한 PHP의 모든 레슨
직접 연습해 보세요: 온라인 PHP 컴파일러