php生成器

Iterator为php提供的生成器接口,实现该接口的下面几个方法后,就可以进行循环遍历。以下是生成器走的流程: 

class Number implements Iterator
{
    protected $i = 1;
    protected $key;
    protected $val;
    protected $count;

    public function __construct($count)
    {
        $this->count = $count;
        echo "第{$this->i}步:对象初始化.</br>";
        $this->i++;
    }

    public function rewind()
    {
        $this->key = 0;
        $this->val = 0;
        echo "第{$this->i}步:rewind()被调用.</br>";
        $this->i++;
    }

    public function next()
    {
        $this->key += 1;
        $this->val += 2;
        echo "第{$this->i}步:next()被调用.</br>";
        $this->i++;
    }

    public function current()
    {
        echo "第{$this->i}步:current()被调用.</br>";
        $this->i++;
        return $this->val;
    }

    public function key()
    {
        echo "第{$this->i}步:key()被调用.</br>";
        $this->i++;
        return $this->key;
    }

    public function valid()
    {
        echo "第{$this->i}步:valid()被调用.</br>";
        $this->i++;
        return $this->key < $this->count;
    }
}

$number = new Number(5);
echo "start...</br>";
foreach ($number as $key => $value) {
    echo "{$key} - {$value}</br>";
}
echo "...end...</br>";

输出的数据是:

第1步:对象初始化.
start...
第2步:rewind()被调用.
第3步:valid()被调用.
第4步:current()被调用.
第5步:key()被调用.
0 - 0
第6步:next()被调用.
第7步:valid()被调用.
第8步:current()被调用.
第9步:key()被调用.
1 - 2
第10步:next()被调用.
第11步:valid()被调用.
第12步:current()被调用.
第13步:key()被调用.
2 - 4
第14步:next()被调用.
第15步:valid()被调用.
第16步:current()被调用.
第17步:key()被调用.
3 - 6
第18步:next()被调用.
第19步:valid()被调用.
第20步:current()被调用.
第21步:key()被调用.
4 - 8
第22步:next()被调用.
第23步:valid()被调用.
...end...

转载自:https://www.cnblogs.com/lynxcat/p/7954456.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值