可见性与不变式
Coddy 面向 C++ 开发者的 PHP 课程的第 33 课,共 48 课。
C++ 和 PHP 都会通过类边界强制执行私有成员访问。将表示保持为私有,并公开能够维护不变量的操作,而不是公开原始写入。访问器返回的引用或对象句柄仍可能暴露可变的共享状态,即使存储是私有的。
private 成员只能由声明它们的类访问。公开能够维护不变量的操作,而不是让调用者写入每个字段。getter 可以安全地公开标量快照,但返回可变对象可能会暴露共享状态。可见性是强制执行的边界,不只是文档说明。
C++ 程序
#include <iostream>
class Meter {int level=4;public:void set(int n){if(n>=0)level=n;}int get()const{return level;}};
int main() {
Meter m;m.set(-1);std::cout<<m.get()<<"\n";
}
程序输出:
4PHP 程序
demo.php
<?php
declare(strict_types=1);
class Secret {private string $value="sealed";public function reveal():string{return $this->value;}} echo (new Secret())->reveal(),"\n";
PHP 输出:
sealed挑战
简单输入是一个整数变化列表。温控器初始值为 20。set(int $value):bool 接受 10..30(含边界),其他值会被拒绝,且状态不会改变。temperature():int 用于读取私有状态。
提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并打印结果。实现模块声明,不要打印内容;不要替换启动脚本,也不要在模块中读取输入。输入符合给定的类型和范围。
编辑 Thermostat.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。
亲手试试
<?php
declare(strict_types=1);
require_once __DIR__."/Thermostat.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function thermostatReport(array $i):int{$t=new Thermostat();foreach($i as $n)$t->set($n);return $t->temperature();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$t=new Thermostat();ensure(!$t->set(9)&&$t->temperature()===20,"private invariant");ensure($t->set(30)&&!$t->set(31)&&$t->temperature()===30,"boundary");
echo (string)thermostatReport($input),"\n";
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C++ 开发者的 PHP中的所有课
自己练习: PHP 在线编译器