PHP 的 只读类

等级 4159 次按键

定义一个 readonly 类(PHP 8.2),所有属性只能在构造函数中设置一次;输出“localhost:8080”。

PHP 代码

// readonly 类(PHP 8.2):所有属性自动成为 readonly
1readonly class Config {
// 提升的属性在构造函数中被赋值一次
2 public function __construct(
3 public string $host,
4 public int $port
5 ) {}
6}
// 之后执行 $c->port = 80; 会抛出 Error
7$c = new Config("localhost", 8080);
// 读取没有问题,输出“localhost:8080”
8echo "$c->host:$c->port";

运行结果

localhost:8080
用这段代码练习打字

可以用这段代码练习打字。成绩不会计入排行榜。

这段代码中的符号

这段 PHP 代码中需要输入的符号及其出现次数。

  • $× 5
  • "× 4
  • _× 2
  • -× 2
  • ,× 2
  • ;× 2
  • (× 2
  • )× 2
  • {× 2
  • }× 2

PHP 等级 4 的更多代码示例

← 返回 PHP 打字练习