Menu
CoddyTech

特征复用实现

Coddy 面向 JavaScript 开发者的 PHP 课程的第 39 课,共 48 课。

JavaScript 可以通过 Object.assign 将方法混入原型,但这是在运行时复制属性,并不是原生的特征系统。PHP 的 use 会插入 trait 的实现,并提供显式的冲突解决语法。trait 既不是可实例化的类,也不能作为接口参数类型。

trait 可以通过 use 为类提供可复用的方法。它不能被实例化,也不是参数的接口类型。trait 将实现复用与继承分开处理。当 trait 发生冲突时,应使用 insteadof 显式解决优先级,并使用 as 创建别名,而不是依赖 include 顺序。

JavaScript 程序

const greeting={hello(){return "hello";}}; class Host {} Object.assign(Host.prototype,greeting); console.log(new Host().hello());

源程序输出:

hello

PHP 程序

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
challenge icon

挑战

简单

输入是一个 ASCII 字符串。Trimmed 特征提供了 clean(string):string,用于返回 trim 的结果。Note 和 Label 都使用 Trimmed。驱动程序会打印两个对象清理后的文本,并用 | 分隔。

提供的 main 脚本会从标准输入读取一个 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";
quiz icon自我测试

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

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

自己练习: PHP 在线编译器