2008-12-29 83 views
1

我目前正在編寫一個類來實現SeekableIterator接口並且遇到問題。我有兩個我正在使用的內部數組,並且希望允許從類外部對它們進行迭代。沒有首先在類中合併兩個數組,有沒有簡單的方法呢?這裏是什麼,我試圖做一個簡單的例子:PHP:實現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; 
} 

回答

1

假設這些陣列都是數字索引,如果當前指數小於

count($this->_books); 

然後返回

$this->_books[$index]; 

否則,如果指數小於count(books)+ count(雜誌),則返回

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

如果兩者都失敗,則可能是OutOfBoundsException。

其他一切都應該落實到位。