Menu
CoddyTech

继承与重写

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

C 语言可以嵌入基础结构体并委托给辅助函数,但它没有类继承或自动虚拟分发。PHP 通过 extends 提供了具有重写规则的单一父类。显式调用父类行为,并对可替换的协作对象使用组合。

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

C 程序

#include <stdio.h>
struct Base { int price; };
struct Child { struct Base base; int fee; };
static int base_total(const struct Base *self, int quantity)
{
    return self->price * quantity;
}
static int child_total(const struct Child *self, int quantity)
{
    return base_total(&self->base, quantity) + self->fee;
}
int main(void)
{
    struct Child child = {{3}, 2};
    printf("%d\n", child_total(&child, 4));
    return 0;
}

源输出:

14

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。保持 Score 独立可用。

提供的主脚本从标准输入读取一个 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自我测试

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

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

自己练习: PHP 在线编译器