PHP 的 魔术方法 __get

等级 4199 次按键

使用魔术方法 __get,从 private 数组返回对未定义或不可访问属性的读取;输出“localhost:3306”。

PHP 代码

1class Config {
// 存放配置的 private 数组
2 private array $d = [
3 "host" => "localhost",
4 "port" => 3306,
5 ];
6
// 读取未定义或不可访问的属性时会调用 __get
7 public function __get(string $k): mixed {
// $k 是属性名;键不存在时返回 null
8 return $this->d[$k] ?? null;
9 }
10}
11
12$c = new Config();
// $c->host 和 $c->port 不存在,因此调用 __get,输出“localhost:3306”
13echo "$c->host:$c->port";

运行结果

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

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

这段代码中的符号

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

  • "× 8
  • $× 7
  • >× 5
  • ;× 4
  • =× 4
  • -× 3
  • _× 2
  • ,× 2
  • :× 2
  • ?× 2

PHP 等级 4 的更多代码示例

← 返回 PHP 打字练习