Menu
CoddyTech

接口采用名义类型

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

C 语言可以通过函数指针表和显式接收者指针来定义可调用约定。PHP 接口是名义型的:类必须通过兼容的方法显式声明 implements。仅靠匹配函数名称并不能建立接口成员关系。请测试同一公共契约的独立实现。

接口命名了一个契约。类必须显式声明 implements;仅仅拥有同名方法并不能使其成为该接口的实例。一个类可以实现多个接口。接口描述公共行为,而实现和状态保存在类中。请使用独立的实现来测试使用者。

C 程序

#include <stdio.h>
#include <stddef.h>
struct Channel {
    const char *prefix;
    void (*send)(const struct Channel *self, const char *text);
};
static void send_prefixed(const struct Channel *self, const char *text)
{
    printf("%s:%s", self->prefix, text);
}
int main(void)
{
    struct Channel channels[] = {
        {"email", send_prefixed}, {"sms", send_prefixed}
    };
    for (size_t i = 0; i < 2; ++i) {
        if (i != 0) {
            putchar('|');
        }
        channels[i].send(&channels[i], "hi");
    }
    putchar('\n');
    return 0;
}

源输出:

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 的费用;数值均为非负数。

提供的主脚本从标准输入读取一个 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自我测试

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

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

自己练习: PHP 在线编译器