在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;
}