PHP 的 闭包绑定

等级 5314 次按键

创建一个绑定到类实例并访问私有属性的闭包。

PHP 代码

// Counter持有一个私有计数
1class Counter {
2 private int $count = 0;
3
// 返回一个会修改私有$count的闭包
4 public function getIncrementer(): Closure {
// 在方法内创建的闭包会自动绑定$this
5 return function(int $step = 1): int {
// 因此它可以访问私有属性
6 $this->count += $step;
7 return $this->count;
8 };
9 }
10}
11
// 创建从0开始的计数器
12$counter = new Counter();
// 获取绑定到该对象的闭包
13$increment = $counter->getIncrementer();
14
// 每次调用都更新同一个$count:输出1、6、7
15echo $increment() . "\n";
16echo $increment(5) . "\n";
17echo $increment();

运行结果

1
6
7
用这段代码练习打字

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

这段代码中的符号

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

  • $× 11
  • ;× 9
  • (× 7
  • )× 7
  • =× 5
  • "× 4
  • -× 3
  • {× 3
  • }× 3
  • >× 3

PHP 等级 5 的更多代码示例

← 返回 PHP 打字练习