Wordsearch – Word Class iterator

An iterator is when a object can be used within a foreach loop and each data item can be looped through, with a couple of other functions declared as well e.g. key, next because these functions allow the foreach loop to work. For example, at the start of the object you will need to have a position indicator (set normally at 0) and a object (array) to go through, I am using the word class from the word search project. From the php.net website there is a more details of a iterator.

The foreach loop basically starts the iterator from the starting point (rewind function) and then using the next function call to increment the internal object to its next point whilst making sure that it has not come to its end point (checking against the valid function).

Here is the code that I have used to demonstrate a iterator interface (interface example).

Please note, extending from the word class from a previous post.

class WordIterator extends Word implements Iterator {
    private $_position = 0;
    private $_wordsIterator;
 
    public function __construct($wordsOrFilename = "words.xml", $maxSearchNum = 5) {
        $this->_position = 0;
	$this->_wordsIterator = array();
 
	parent::__construct($wordsOrFilename, $maxSearchNum);
 
	$this->_wordsIterator = parent::wordsArray();
    }
 
    function rewind() {
        $this->_position = 0;
    }
 
    function current() {
        return $this->_wordsIterator[$this->_position];
    }
 
    function key() {
        return $this->_position;
    }
 
    function next() {
        ++$this->_position;
    }
 
    function valid() {
        return isset($this->_wordsIterator[$this->_position]);
    }
}
 
 
$WordIt = new WordIterator;
 
foreach($WordIt as $key => $value) {
    echo $key . " " . $value;
    echo "\n";
}

Output would be

0 merry
1 old 
2 sole 
3 was 
4 he

Leave a Reply

Your email address will not be published. Required fields are marked *