继承与重写
Coddy 面向 Luau 开发者的 PHP 课程的第 35 课,共 48 课。
Luau 的元表 __index 链可以提供类似原型的回退行为,但它没有内置的类继承语法。PHP 的 extends 会指定一个父类,并遵循重写和可见性规则。请有意识地转换查找和委托行为,不要把元表当作完全相同的类。
一个类最多只能继承一个父类。重写的方法必须遵守兼容的可见性和类型规则。parent::method 会调用父类的实现;仅仅重写方法并不会调用父类实现。对于真正可替换的关系,优先使用继承;对于可替换的协作者,优先使用组合。在声明的位置使用 final 可以阻止进一步扩展或重写。
Luau 程序
local Base={name=function()return "base" end};local Child=setmetatable({name=function()return "child" end},{__index=Base});print(Child.name())
源程序输出:
childPHP 程序
Message.php
<?php
declare(strict_types=1);
class Message {public function text():string{return "base";}}
LoudMessage.php
<?php
declare(strict_types=1);
require_once __DIR__."/Message.php";class LoudMessage extends Message {public function text():string{return strtoupper(parent::text());}}
demo.php
<?php
declare(strict_types=1);
require_once __DIR__."/LoudMessage.php";echo (new LoudMessage())->text(),"\n";
PHP 输出:
BASE挑战
简单输入为 [base,extra],表示非负整数分数。Score(base) 的 points():int 方法返回 base。BonusScore(base,extra) 扩展 Score,初始化父类,并重写 points 以加上 extra。确保 base 仍可单独使用。
提供的 main 脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。实现模块声明,不要打印内容;不要替换启动脚本,也不要从模块读取输入。输入符合所述类型和范围。
编辑 Score.php、BonusScore.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。
亲手试试
<?php
declare(strict_types=1);
require_once __DIR__."/Score.php";
require_once __DIR__."/BonusScore.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 Score(2))->points()===2,"base");$s=new BonusScore(4,3);ensure($s instanceof Score && $s->points()===7,"override");
echo (string)(new BonusScore(...$input))->points(),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Luau 开发者的 PHP中的所有课
自己练习: PHP 在线编译器