Menu
CoddyTech

接口采用名义类型

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

Dart 类会公开接口,而 implements 要求声明相应成员,但不会继承它们的实现。PHP 使用显式的接口声明和 implements 来表明名义上的成员关系。仅仅方法名相同,并不意味着 PHP 对象实现了所需的接口。

接口定义了一份契约。类必须显式声明 implements;仅仅拥有名称匹配的方法,并不会使它成为该接口的实例。一个类可以实现多个接口。接口描述公开行为,而实现和状态则位于类中。使用独立的实现来测试使用者。

Dart 程序

abstract interface class Channel {String send(String text);}
class Email implements Channel {String send(String text)=>"email:$text";}
class Sms implements Channel {String send(String text)=>"sms:$text";}
void main() {
final channels=<Channel>[Email(),Sms()]; print(channels.map((c)=>c.send("hi")).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自我测试

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

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

自己练习: PHP 在线编译器