php iterator接口

在laravel中有大量的类实现了Iterator接口,使其可以使用foreach()进行遍历,所以自己写了个例子来加深理解

laravel中实现了该接口的例子有①分页 Illuminate\Pagination\LengthAwarePaginator ②查询构造器返回结果Collection

 

<?php
class testsIterator implements \Iterator
{
    protected $data;//一维索引数组
    protected $key=0;//记录index

    public function add($str){//添加数据
        $this->data[]=$str;
    }
    /**
     * Return the current element
     * @link http://php.net/manual/en/iterator.current.php
     * @return mixed Can return any type.
     * @since 5.0.0
     */
    public function current()
    {
        return $this->data[$this->key];
    }

    /**
     * Move forward to next element
     * @link http://php.net/manual/en/iterator.next.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function next()
    {
        $this->key++;
    }

    /**
     * Return the key of the current element
     * @link http://php.net/manual/en/iterator.key.php
     * @return mixed scalar on success, or null on failure.
     * @since 5.0.0
     */
    public function key()
    {
        return $this->key;
    }

    /**
     * Checks if current position is valid
     * @link http://php.net/manual/en/iterator.valid.php
     * @return boolean The return value will be casted to boolean and then evaluated.
     * Returns true on success or false on failure.
     * @since 5.0.0
     */
    public function valid()
    {
        return $this->key <0 ? false:$this->key > count($this->data)-1 ? false:true;
    }

    /**
     * Rewind the Iterator to the first element
     * @link http://php.net/manual/en/iterator.rewind.php
     * @return void Any returned value is ignored.
     * @since 5.0.0
     */
    public function rewind()
    {
        $this->key=0;
    }
}

$tests=new testsIterator();
$tests->add('apple');
$tests->add('peach');
$tests->add('banana');
$tests->add('ambrella');

foreach($tests as $test){
	echo $test;
}

 

转载于:https://www.cnblogs.com/xueleixi/p/5443553.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值