Menu
CoddyTech

接口按名称匹配

Coddy 面向 Kotlin 开发者的 PHP 课程的第 36 课,共 48 课。

Kotlin 接口会定义契约,也可以包含默认实现。PHP 接口同样要求通过 implements 显式声明实现,但实现的复用属于类或 trait。仅仅方法名称相同,并不能让 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: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自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 Kotlin 开发者的 PHP中的所有课

自己练习: PHP 在线编译器