可见性与不变量
Coddy 面向 C# 开发者的 PHP 课程的第 33 课,共 48 课。
C# 和 PHP 都会强制执行私有成员的访问限制,但 C# 还支持程序集内部可见性和 PHP 中没有的复合访问修饰符。C# 属性可以公开 getter,同时将 setter 设为私有;PHP 8.3 要实现类似的受控行为,需要使用显式方法,而不是 PHP 8.4 的属性功能。
私有成员只能由声明它们的类访问。你应该公开能够保持不变量的操作,而不是让调用者随意写入每个字段。getter 可以安全地公开标量快照,但返回可变对象可能会暴露共享状态。可见性是强制执行的边界,不只是文档说明。
C# 程序
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Secret{private string value="sealed";public string Reveal(){return value;}}
static void Main() {
Console.WriteLine(new Secret().Reveal());
}
}源代码输出:
sealedPHP 程序
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 用于读取私有状态。
提供的 main 脚本会从标准输入读取一个 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 在线编译器