1

我目前正在编写一个实现 SeekableIterator 接口的类并且遇到了问题。我有两个正在使用的内部数组,并希望允许从类外部对它们进行迭代。有没有一种简单的方法可以在不首先合并类中的两个数组的情况下做到这一点?这是我正在尝试做的一个简单示例:

class BookShelf implements ArrayAccess, Countable, SeekableIterator {
    protected $_books = array(...);
    protected $_magazines = array(...);

    /**** CLASS CONTENT HERE ****/
}

$shelf = new BookShelf();

// Loops through both arrays, first books (if any) and then magazines (if any)
foreach($shelf as $item) {
    echo $item;
}
4

1 回答 1

1

假设这些数组都是数字索引的,如果当前索引小于

count($this->_books);

然后返回

$this->_books[$index];

否则,如果索引小于 count(books)+count(magazines),则返回

$this->_magazines[$index-count($this->_books)]

如果两者都失败,可能会出现 OutOfBoundsException。

其他一切都应该到位。

于 2008-12-29T19:42:26.387 回答