为此,我编写了这个类来使用回调。用法:
$array = new ArrayIterator(array(1,2,3,4,5));
$doubles = new ModifyIterator($array, function($x) { return $x * 2; });
定义(根据需要随意修改):
class ModifyIterator implements Iterator {
/**
* @var Iterator
*/
protected $iterator;
/**
* @var callable Modifies the current item in iterator
*/
protected $callable;
/**
* @param $iterator Iterator|array
* @param $callable callable This can have two parameters
* @throws Exception
*/
public function __construct($iterator, $callable) {
if (is_array($iterator)) {
$this->iterator = new ArrayIterator($iterator);
}
elseif (!($iterator instanceof Iterator))
{
throw new Exception("iterator must be instance of Iterator");
}
else
{
$this->iterator = $iterator;
}
if (!is_callable($callable)) {
throw new Exception("callable must be a closure");
}
if ($callable instanceof Closure) {
// make sure there's one argument
$reflection = new ReflectionObject($callable);
if ($reflection->hasMethod('__invoke')) {
$method = $reflection->getMethod('__invoke');
if ($method->getNumberOfParameters() !== 1) {
throw new Exception("callable must have only one parameter");
}
}
}
$this->callable = $callable;
}
/**
* Alters the current item with $this->callable and returns a new item.
* Be careful with your types as we can't do static type checking here!
* @return mixed
*/
public function current()
{
$callable = $this->callable;
return $callable($this->iterator->current());
}
public function next()
{
$this->iterator->next();
}
public function key()
{
return $this->iterator->key();
}
public function valid()
{
return $this->iterator->valid();
}
public function rewind()
{
$this->iterator->rewind();
}
}