萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 迭代器實作斐波納契數列:無限序列的記憶體高效生成

迭代器模式優勢

實作 Iterator 介面,即可在 foreach 中逐個產生值,無需一次性產生整個陣列,記憶體佔用 O(1),適合無限或超大數列。

完整 Fibonacci 迭代器

<?php
class Fibonacci implements Iterator
{
    private int $previous = 1;
    private int $current  = 0;
    private int $key      = 0;

    public function current(): mixed { return $this->current; }
    public function key(): mixed     { return $this->key; }

    public function next(): void
    {
        $newPrev = $this->current;
        $this->current += $this->previous;
        $this->previous = $newPrev;
        $this->key++;
    }

    public function rewind(): void
    {
        $this->previous = 1;
        $this->current  = 0;
        $this->key      = 0;
    }

    public function valid(): bool { return true; } // 無限序列永遠有效
}

// 使用
$seq = new Fibonacci();
foreach ($seq as $i => $val) {
    echo "$val ";
    if ($i >= 15) break;
}
// 輸出:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610
?>

Generator 更簡潔寫法(PHP 5.5+)

function fibonacciGen(): \Generator
{
    $prev = 1;
    $curr = 0;
    while (true) {
        yield $curr;
        [$prev, $curr] = [$curr, $prev + $curr];
    }
}

foreach (fibonacciGen() as $i => $val) {
    echo "$val ";
    if ($i >= 15) break;
}

應用場景延伸

  • 大檔案逐行讀取(yield 替代 fgets() 迴圈)
  • 資料庫大結果集分批處理
  • 無限流資料管線(日誌、感測器、訊息佇列)
  • 組合多個迭代器(AppendIterator、FilterIterator)

介面契約提醒

實作 Iterator 必須完整定義五個方法;IteratorAggregate 僅需 getIterator() 回傳任一 Traversable,更輕量。

copyright © 萬盛學電腦網 all rights reserved