問題描述
如果我有一個實現 Iterator
接口的類,我可以手動控制 foreach
循環中的迭代方式.但是還有其他方法可以讓我的對象表現得像一個數組嗎?
If I have a class that implements the Iterator
interface, I can manually control how iteration in a foreach
loop. But are there other ways in which I could make my object behave like an array?
例如,假設我有一個實現 Iterator
的類 Guestbook
,這樣我就可以迭代 foreach (new Guestbook() as $entry)代碼>.但是,如果我想顛倒順序怎么辦?
For instance, let's say I have a class Guestbook
which implements Iterator
, so that I can iterate foreach (new Guestbook() as $entry)
. But what if I want to, say, reverse the order?
foreach (array_reverse(new Guestbook()) as $entry)
肯定不行,因為 array_reverse
只接受一個數組.
foreach (array_reverse(new Guestbook()) as $entry)
definitely won't work, because array_reverse
will only accept an array.
我想我想問的是,我可以將 Iterator
用于更多的 foreach
循環嗎?
I guess what I'm asking is, can I use Iterator
for more than just foreach
loops?
謝謝.
推薦答案
迭代器接口的目的 是為了讓你的對象在 foreach 循環中使用,它不是為了讓你的對象像一個數組.如果您想要一些像數組一樣的東西,請使用數組.
The purpose of the Iterator interface is to allow your object to be used in a foreach loop, it is not intended to make your object act like an array. If you want something that acts like an array, use an array.
您始終可以使用iterator_to_array 函數將您的對象轉換為數組,但您無法逆轉該過程.
You can always turn your object into an array by using the iterator_to_array function, but you can't reverse that process.
如果您認為需要反轉可迭代對象中元素的順序,那么您可以創建一個 reverse() 方法,該方法可能在內部使用 array_reverse().像這樣:-
If you see the need for reversing the order of the elements in your iterable object, then you could create a reverse() method that, possibly, uses array_reverse() internally. Something like this:-
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
我寫了代碼是為了在發布之前向自己證明它可以工作,并認為我不妨把它扔到答案中.
I wrote the code to prove to myself that it would work before posting and thought I might as well throw it into the answer.
這篇關于將實現 Iterator 的 PHP 類視為數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!