使对象可以像数组一样进行foreach循环,要求属性必须是私有

class myIterator implements Iterator
{
    private $var = array(1, 2, 3, 4, 5);
    
    public function __construct(){}

    public function rewind()
    {
        reset($this->var);
    }

    public function current()
    {
        return current($this->var);
    }

    public function key()
    {
        return key($this->var);
    }

    public function next()
    {
        return next($this->var);
    }

    public function valid()
    {
        return ($this->current() !== false);
    }
}
 
$it = new myIterator;
foreach($it as $key => $value) {
    echo "$key=>$value\n";
}

posted on 2019-02-01 14:31  果然朝辉  阅读(748)  评论(0编辑  收藏  举报

导航