php中的迭代器

php中的迭代器示例

定义

class Iterator extends Traversable {
/* 方法 */
abstract public current(): mixed
abstract public key(): scalar
abstract public next(): void
abstract public rewind(): void
abstract public valid(): bool
}

示例


class DemoIterator implements Iterator {
    private $_test = array("one", "two", "three");

    private $_key = 0;
    private $_step = 0;

    public function current() {
        $this->show_step(__METHOD__);
        return $this->_test[$this->_key];
    }

    public function key() {
        $this->show_step(__METHOD__);
        return $this->_key;
    }


    public function next() {
        $this->show_step(__METHOD__);
        $this->_key++;
    }


    public function valid() {
        $this->show_step(__METHOD__);
        return isset($this->_test[$this->_key]);
    }

    public function rewind() {
        $this->show_step(__METHOD__);
        $this->_key = 0;
    }

    private function show_step($method) {
        $this->_step++;
        echo "[步骤 $this->_step ] 执行  $method" . PHP_EOL;
    }
}

$iterator = new DemoIterator();
foreach($iterator as $key => $value){
    echo "$key => $value" . PHP_EOL;
}

输出

[步骤 1 ] 执行  DemoIterator::rewind
[步骤 2 ] 执行  DemoIterator::valid
[步骤 3 ] 执行  DemoIterator::current
[步骤 4 ] 执行  DemoIterator::key
0 => one
[步骤 5 ] 执行  DemoIterator::next
[步骤 6 ] 执行  DemoIterator::valid
[步骤 7 ] 执行  DemoIterator::current
[步骤 8 ] 执行  DemoIterator::key
1 => two
[步骤 9 ] 执行  DemoIterator::next
[步骤 10 ] 执行  DemoIterator::valid
[步骤 11 ] 执行  DemoIterator::current
[步骤 12 ] 执行  DemoIterator::key
2 => three
[步骤 13 ] 执行  DemoIterator::next
[步骤 14 ] 执行  DemoIterator::valid