PHP 的 观察者模式
等级 5279 次按键
实现简单的事件总线来注册和触发事件回调。
PHP 代码
1class Bus { // 按事件名分组保存处理函数2 private array $h = [];3 // 为事件注册处理函数4 public function on(5 string $e, callable $f6 ) { // []表示追加,$e对应的列表在首次使用时创建7 $this->h[$e][] = $f;8 }9 // 用数据$d执行该事件的所有处理函数10 public function fire(string $e, $d) { // ?? []避免事件没有处理函数时产生警告11 foreach ($this->h[$e] ?? [] as $f) {12 $f($d);13 }14 }15}16 17$b = new Bus();// 为“msg”事件注册一个箭头函数18$b->on("msg", fn($t) => print("$t!\n"));// 处理函数被执行,输出hello!19$b->fire("msg", "hello");运行结果
hello!
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 PHP 代码中需要输入的符号及其出现次数。
$× 18(× 9)× 9"× 8;× 6[× 5]× 5>× 5-× 4,× 4