Iterator & foreach

<?php
class Traverable {

}

abstract class Iterator extends Traverable {
    abstract public function current();
    abstract public function key();
    abstract public function next();
    abstract public function rewind();
    abstract public function valid();
}

class myIterator implements Iterator

{

    private $position = 0;

    private $array = [

        "firstelement",

        "secondelement",

        "lastelement",

    ];

    public function __construct()

    {

        $this->position = 0;

    }

    function rewind()

    {

        var_dump(__METHOD__);

        $this->position = 0;

    }

    function current()

    {

        var_dump(__METHOD__);

        return $this->array[$this->position];

    }

    function key()

    {

        var_dump(__METHOD__);

        return $this->position;

    }

    function next()

    {

        var_dump(__METHOD__);

        ++$this->position;

    }

    function valid()

    {

        var_dump(__METHOD__);

        return isset($this->array[$this->position]);

    }

}

$it = new myIterator;

foreach ($it as $key => $value) {

    var_dump($key, $value);

    echo "\n";

}
本作品采用《CC 协议》,转载必须注明作者和本文链接
烧杯凉白开
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!