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);// カウンターが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