接口是名义类型
Coddy 面向 Rust 开发者的 PHP 课程的第 36 课,共 48 课。
Rust trait 实现声明了行为契约,泛型或 dyn trait 对象决定分发方式。PHP 接口要求显式使用 implements,并提供兼容的公共方法。仅仅方法名称相同,并不能确立名义上的成员关系,而且 PHP 的泛型和生命周期能力有所不同。
接口定义了一种契约。类必须显式声明 implements;仅仅拥有名称相同的方法,并不会使它成为该接口的实例。一个类可以实现多个接口。接口描述公共行为,而实现和状态由类负责。使用一个独立的实现来测试使用方。
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: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 会加上该金额。驱动程序使用金额为 three 的费用;值均为非负数。
提供的 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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Rust 开发者的 PHP中的所有课
自己练习: PHP 在线编译器