接口采用名义类型
Coddy 面向 Swift 开发者的 PHP 课程的第 36 课,共 48 课。
Swift 协议要求显式声明遵循,并且可以由类、结构体和枚举采用。PHP 接口要求类使用 implements,并提供兼容的公共方法。仅仅方法名称相同并不能确立名义上的成员关系,Swift 的值语义也不会自动延续到 PHP。
接口定义了一份契约。类必须显式声明 implements;仅仅拥有名称相同的方法,并不会让它成为该接口的实例。一个类可以实现多个接口。接口描述公共行为,而实现和状态由类承担。使用独立的实现来测试使用者。
Swift 程序
protocol Channel { func send(_ text: String) -> String }
struct Email: Channel { func send(_ text: String) -> String { "email:" + text } }
struct Sms: Channel { func send(_ text: String) -> String { "sms:" + text } }
let channels: [any Channel] = [Email(), Sms()]
print(channels.map { $0.send("hi") }.joined(separator: "|"))
源程序输出:
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 的费用;值均为非负数。
提供的主脚本会从标准输入读取一个 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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Swift 开发者的 PHP中的所有课
自己练习: PHP 在线编译器