Re: Cannot use foreach() with $this->my_iterator within a class

php.internals

Marc Dembogurski

22 years ago
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

Philip Fletcher

22 years ago
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: