我目前正在编写一个实现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;
}发布于 2008-12-29 19:42:26
假设这两个数组都是数字索引的,如果当前索引小于
count($this->_books);然后返回
$this->_books[$index];否则,如果索引小于count(图书)+count(杂志),则返回
$this->_magazines[$index-count($this->_books)]如果两个都失败,则OutOfBoundsException可能是正常的。
其他的一切都应该井井有条。
https://stackoverflow.com/questions/398398
复制相似问题