PHP 的 自定义迭代器

等级 5298 次按键

实现带有类迭代器hasNext和next方法的计数器类。

PHP 代码

// 具有类似迭代器接口的计数器
1class Counter {
// 当前位置
2 private int $cur;
3
// $max通过属性提升定义,$cur从0开始
4 public function __construct(
5 private int $max
6 ) {
7 $this->cur = 0;
8 }
9
// 还有剩余值时返回true
10 public function hasNext(): bool {
11 return $this->cur < $this->max;
12 }
13
// 返回当前值,然后前进
14 public function next(): int {
// 后置自增返回自增前的值
15 return $this->cur++;
16 }
17}
18
19$c = new Counter(5);
// 循环直到计数器到达5
20while ($c->hasNext()) {
// 输出0 1 2 3 4
21 echo $c->next() . " ";
22}

运行结果

0 1 2 3 4 
用这段代码练习打字

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

这段代码中的符号

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

  • $× 9
  • (× 7
  • )× 7
  • -× 6
  • ;× 6
  • >× 6
  • {× 5
  • }× 5
  • _× 2
  • :× 2

PHP 等级 5 的更多代码示例

← 返回 PHP 打字练习