继承与重写
Coddy 面向 Java 开发者的 PHP 课程的第 35 课,共 48 课。
Java 和 PHP 都可以继承一个父类,并实现多个接口。Java 中的 super.method 对应于 PHP 中显式调用 parent::method,但构造函数和类型兼容性方面仍需注意。Java 使用 @Override 让编译器进行检查;PHP 则有自己的运行时类检查。
一个类最多只能继承一个父类。重写的方法必须遵循兼容的可见性和类型规则。parent::method 会调用父类的实现;仅仅重写并不会调用父类的方法。只有在确实存在可替换的关系时才使用继承,对于可替换的协作者则使用组合。在声明 final 的位置,final 会阻止进一步扩展或重写。
Java 程序
import java.util.*;
class Main {
static class Message{String text(){return "base";}}
static class LoudMessage extends Message{@Override String text(){return super.text().toUpperCase(Locale.ROOT);}}
public static void main(String[] args) throws Exception {
System.out.println(new LoudMessage().text());
}
}源程序输出:
BASEPHP 程序
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";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 Java 开发者的 PHP中的所有课
自己练习: PHP 在线编译器