继承与重写
Coddy 面向 Swift 开发者的 PHP 课程的第 35 课,共 48 课。
Swift 类继承使用一个父类,替换继承的方法时必须使用 override;结构体不会继承其他结构体。PHP 的 extends 也只能指定一个父类,并有自己的重写规则。要有意识地委托给父类行为,并使用组合来处理可替换的依赖项。
一个类最多只能继承一个父类。重写的方法必须遵循兼容的可见性和类型。parent::method 会调用父类的实现;仅仅重写并不会调用它。对于真正可替换的关系,优先使用继承;对于可替换的协作者,优先使用组合。final 会阻止声明处的进一步扩展或重写。
Swift 程序
class Base { func value() -> Int { 3 } }
final class Child: Base { override func value() -> Int { super.value() } }
print(Child().value())
源代码输出:
3PHP 程序
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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Swift 开发者的 PHP中的所有课
自己练习: PHP 在线编译器