如果我有一个实现Iterator
接口的类,我可以手动控制foreach
循环中的迭代方式。但还有其他方法可以让我的对象像数组一样吗?
例如,假设我有一个实现Guestbook
的类Iterator
,以便我可以迭代foreach (new Guestbook() as $entry)
。但是,如果我想要反转订单怎么办?
foreach (array_reverse(new Guestbook()) as $entry)
肯定不起作用,因为array_reverse
只接受数组。
我想我要问的是,我可以将Iterator
用于foreach
次以上的循环吗?
感谢。
答案 0 :(得分:17)
Iterator interface的目的是允许您的对象在foreach循环中使用,而不是让您的对象像数组一样。如果你想要一个像数组一样的东西,使用一个数组。
您始终可以使用iterator_to_array function将对象转换为数组,但无法撤消该过程。
如果您认为需要反转可迭代对象中元素的顺序,那么您可以创建一个reverse()方法,该方法可能在内部使用array_reverse()。这样的事情: -
class Test implements Iterator
{
private $testing = [0,1,2,3,4,5,6,7,8,9,10];
private $index = 0;
public function current()
{
return $this->testing[$this->index];
}
public function next()
{
$this->index ++;
}
public function key()
{
return $this->index;
}
public function valid()
{
return isset($this->testing[$this->key()]);
}
public function rewind()
{
$this->index = 0;
}
public function reverse()
{
$this->testing = array_reverse($this->testing);
$this->rewind();
}
}
$tests = new Test();
var_dump(iterator_to_array($tests));
$tests->reverse();
var_dump(iterator_to_array($tests));
输出: -
array (size=11)
0 => int 0
1 => int 1
2 => int 2
3 => int 3
4 => int 4
5 => int 5
6 => int 6
7 => int 7
8 => int 8
9 => int 9
10 => int 10
array (size=11)
0 => int 10
1 => int 9
2 => int 8
3 => int 7
4 => int 6
5 => int 5
6 => int 4
7 => int 3
8 => int 2
9 => int 1
10 => int 0
我写了一些代码来向自己证明它在发布之前会起作用,并且我认为我可能会把它放到答案中。
答案 1 :(得分:2)
在班级中实施ArrayAccess
。
请参阅此处的文档:http://www.php.net/arrayaccess
答案 2 :(得分:1)
来自PHP
Introduction
Interface for external iterators or objects that can be iterated themselves internally.
正如您从界面中看到的那样 目录¶
Iterator::current — Return the current element
Iterator::key — Return the key of the current element
Iterator::next — Move forward to next element
Iterator::rewind — Rewind the Iterator to the first element
Iterator::valid — Checks if current position is valid
该操作设计用于前向迭代。因此反向自然不起作用,并不是为此而设计的。
有关更多与数组对象相关的接口,请查看。 ArrayAccess和Countable
对于反向对象迭代器的解决方案,请在此处查看答案 Iterate in reverse through an array with PHP - SPL solution?