IteratorAggregate
是一个创建外部迭代器的接口(interface):
class myData implements IteratorAggregate
{
public $property1 = "Public property one";
public $property2 = "Public property two";
public $property3 = "Public property three";
public function __construct()
{
$this->property4 = "last property";
}
public function getIterator()
{
return new ArrayIterator($this);
}
}
$obj = new myData;
并且您将能够使用 foreach
遍历对象:
foreach($obj as $key => $value) {
var_dump($key, $value);
echo "\n";
}
虽然 Iterator
是一个外部迭代器或可以在内部迭代自身的对象的接口(interface):
class myIterator implements Iterator
{
private $position = 0;
private $array = array('one', 'two', 'three');
function rewind()
{
$this->position = 0;
}
function current()
{
return $this->array[$this->position];
}
function key()
{
return $this->position;
}
function next()
{
++$this->position;
}
function valid()
{
return isset($this->array[$this->position]);
}
}
同样,您可以用基本相同的方式遍历它:
$it = new myIterator;
foreach($it as $key => $value) {
var_dump($key, $value);
echo "\n";
}
那么谁能解释一下为什么我们需要两个接口(interface),它们之间有什么区别?
最佳答案
我假设 IteratorAggregate
适用于您想要节省时间的情况,而 Iterator
适用于您需要对对象的迭代进行精细控制的情况。例如,它允许您在 next()
、key()
或 prev()
失败时添加自定义异常、缓存(如果您遍历某些内容通过网络获取数据),在返回值之前对其进行预处理。
关于PHP 接口(interface) IteratorAggregate vs Iterator?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13624639/