特征复用实现
Coddy 面向 C 开发者的 PHP 课程的第 39 课,共 48 课。
C 语言通过辅助函数、函数指针和组合而非 Trait 特性来实现代码复用。PHP Trait 通过 use 将可复用的方法插入类中。它们不是可实例化的对象,也不是参数的接口类型,出现冲突时需要显式解决。
Trait 通过 use 为类提供可复用的方法。它不能被实例化,也不是用于参数的接口类型。Trait 将实现复用与继承分离开来。当 Trait 发生冲突时,需使用 insteadof 显式解决优先级,并使用 as 设置别名,而不是依赖包含顺序。
C 程序
#include <stdio.h>
static const char *hello(void){return "hello";}
struct Host{const char *(*greet)(void);};
int main(void) {
struct Host host={hello};puts(host.greet());
return 0;
}
源输出:
helloPHP 程序
Greeting.php
<?php
declare(strict_types=1);
trait Greeting {public function hello():string{return "hello";}}
Host.php
<?php
declare(strict_types=1);
require_once __DIR__."/Greeting.php";class Host {use Greeting;}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/Host.php";echo (new Host())->hello(),"\n";
PHP 输出:
hello挑战
简单输入是一个 ASCII 字符串。Trimmed trait 提供 clean(string):string,返回 trim 后的结果。Note 和 Label 都使用 Trimmed。主程序打印两者清理后的文本,中间用 | 分隔。
提供的主脚本从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。实现模块声明时不要进行任何打印;不要替换启动脚本或在模块中读取输入。输入符合指定的类型和范围。
编辑 Trimmed.php、Note.php、Label.php。main.php 是被锁定的入口文件。依赖项使用带有相对文件名路径的 require_once __DIR__。
亲手试试
<?php
declare(strict_types=1);
require_once __DIR__."/Trimmed.php";
require_once __DIR__."/Note.php";
require_once __DIR__."/Label.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);
ensure((new Note())->clean(" z ")==="z" && (new Label())->clean(" y ")==="y","shared trait");
echo (new Note())->clean($input)."|".(new Label())->clean($input),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C 开发者的 PHP中的所有课
自己练习: PHP 在线编译器