Re: Iterator Class/foreach Logic Flaw? (was: [PHP-DEV] Cannot use foreach() with $this->my_iterator within a class)

From: Date: Tue, 02 Mar 2004 20:37:36 +0000
Subject: Re: Iterator Class/foreach Logic Flaw? (was: [PHP-DEV] Cannot use foreach() with $this->my_iterator within a class)
References: 1  Groups: php.internals 
Request: Send a blank email to internals+get-8319@lists.php.net to get a copy of this message
Hi Marc Please take a look at the thread headed 'Iterator Class/foreach Logic Flaw?' - you will find your hasMore() returns TRUE when place on the last element, but (in the exammple code below), there are only three elements - therefore when on the third element, hasMore() should return false... This thread is a different (possible) bug - the foreach() construct silently stops all php processing when called using a class member as the iterator. Regards Philip Example code: <?php class MyIterator implements Iterator { private $container = array('one', 'two', 'three'); //Incorrectly returns true on last element public function hasMore(){ if (key($this->container) === NULL ) return FALSE; if ( (key($this->container)) <= (count($this->container)-1) ) { return TRUE; } else { return FALSE; } } public function rewind() { reset($this->container); } function key() { return key($this->container); } function current() { return current($this->container); } function next() { next($this->container); } } $i = new MyIterator(); foreach($i as $key => $value) { echo '<br />Current value: ' . $value . '. Calling hasMore() : '; var_dump($i->hasMore()); } echo ' - last row *should* return false.'; ?> Marc Dembogurski wrote: > Hi, > > I used to implement the hasMore() method like this: > > public function hasMore(){ > if (key($this->container) === NULL ) return FALSE; > if ( (key($this->container)) <= > (count($this->container)-1) ) > { > return TRUE; > }else > return FALSE; > } > > And I think that is what hasMore means, "If an array > has more elements from the current position". > > But it should be available at anywhere Users want > use it. Not only at foreach. > > Regards, > Marc > > > __________________________________ > Do you Yahoo!? > Yahoo! Search - Find what you’re looking for faster > http://search.yahoo.com

« previous php.internals (#8319) next »