PHP 的 自定义迭代器
等级 5298 次按键
实现带有类迭代器hasNext和next方法的计数器类。
PHP 代码
// 具有类似迭代器接口的计数器1class Counter { // 当前位置2 private int $cur;3 // $max通过属性提升定义,$cur从0开始4 public function __construct(5 private int $max6 ) {7 $this->cur = 0;8 }9 // 还有剩余值时返回true10 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);// 循环直到计数器到达520while ($c->hasNext()) { // 输出0 1 2 3 421 echo $c->next() . " ";22}运行结果
0 1 2 3 4
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 PHP 代码中需要输入的符号及其出现次数。
$× 9(× 7)× 7-× 6;× 6>× 6{× 5}× 5_× 2:× 2