<?php
/*
* Iterater 简单模式
*/
class sample implements Iterator
{
private $_items ;
public function __construct(&$data) {
$this->_items = $data;
}
public function current() { //当前值
return current($this->_items);
}
public function next() { //移动指针到下一位
next($this->_items);
}
public function key() { //当前键
return key($this->_items);
}
public function rewind() { //初始化指针
reset($this->_items);
}
public function valid() {
return ($this->current() !== FALSE);
}
}
/** DEMO */
$data = array(1,'kiy'=>1, 2, 3, 4, 5);
$sa = new sample($data);
echo 'curr'. $sa->current() .'<br/>';
print_r($sa->key()); echo '<br/>';
$sa->rewind();
print_r($sa->valid()); echo 'valid<br/>';
foreach ($sa AS $key => $row) {
echo $key, ' ', $row, '<br />';
}
/*
* 文件迭代器
*/
class RecursiveFileFilterIterator extends FilterIterator
{
// 满足条件的扩展名
protected $ext = array('jpg','gif');
/**
* 提供 $path 并生成对应的目录迭代器
*/
public function __construct($path)
{
parent::__construct(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)));
}
/**
* 检查文件扩展名是否满足条件
*/
public function accept()
{
$item = $this->getInnerIterator();
if ($item->isFile() && in_array(pathinfo($item->getFilename(), PATHINFO_EXTENSION), $this->ext))
{
return TRUE;
}
}
}
// 实例化
foreach (new RecursiveFileFilterIterator('D:/') as $item)
{
echo $item . PHP_EOL;
}