继承与方法重写
Coddy 面向 Kotlin 开发者的 PHP 课程的第 35 课,共 48 课。
Kotlin 中的类和成员默认是 final,要进行普通的子类化或重写,需要将它们声明为 open。PHP 中的类和普通方法通常可以扩展,除非受到限制。保留预期的扩展点,并有意调用父类的行为。
一个类最多只能继承一个父类。重写方法必须遵循兼容的可见性和类型。parent::method 会调用父类的实现;仅仅重写并不会调用它。只有在确实存在可替代关系时才优先使用继承,可替换的协作者则使用组合。声明 final 的地方会阻止进一步扩展或重写。
Kotlin 程序
open class Base {open fun value()=3}
class Child:Base()
fun main(){
println(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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Kotlin 开发者的 PHP中的所有课
自己练习: PHP 在线编译器