Menu
CoddyTech

继承与重写

Coddy 面向 GDScript 开发者的 PHP 课程的第 35 课,共 48 课。

GDScript 的 extends 机制会继承一个基类,重写的方法可以调用 super,将调用委托给基类。PHP 的 extends 和 parent 调用作用类似,但遵循 PHP 特有的可见性和签名规则。如果某个依赖需要独立于继承层次结构进行替换,优先使用组合。

一个类最多只能继承一个父类。重写的方法必须遵循兼容的可见性和类型。parent::method 会调用父类的实现;仅仅重写方法并不会调用父类实现。只有在确实存在可替换关系时才优先使用继承;对于可以替换的协作对象,则优先使用组合。在声明的位置使用 final,可以阻止进一步扩展或重写。

GDScript 程序

extends SceneTree
class Base:
    var price = 5
    func total(quantity):
        return price * quantity
class Delivery extends Base:
    var fee = 2
    func total(quantity):
        return super.total(quantity) + fee
func _init():
    var delivery = Delivery.new()
    print(str(delivery.total(3)) + ":" + str(delivery.total(0)))
    quit()

程序输出:

17:2

PHP 程序

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

挑战

简单

输入是 [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";
quiz icon自我测试

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

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

自己练习: PHP 在线编译器