php - some questions about the usage of Iterator function -
code from:http://php.net/manual/en/class.iterator.php(example #1 basic usage)
<?php class myiterator implements iterator { private $position = 0; private $array = array( "firstelement", "secondelement", "lastelement", ); public function __construct() { $this->position = 0; } function rewind() { var_dump(__method__); $this->position = 0; } function current() { var_dump(__method__); return $this->array[$this->position]; } function key() { var_dump(__method__); return $this->position; } function next() { var_dump(__method__); ++$this->position; } function valid() { var_dump(__method__); return isset($this->array[$this->position]); } } $it = new myiterator; foreach($it $key => $value) { var_dump($key, $value); echo "\n"; } ?>
output is:
string 'myiterator::rewind' (length=18) string 'myiterator::valid' (length=17) string 'myiterator::current' (length=19) string 'myiterator::key' (length=15) int 0 string 'firstelement' (length=12) string 'myiterator::next' (length=16) string 'myiterator::valid' (length=17) string 'myiterator::current' (length=19) string 'myiterator::key' (length=15) int 1 string 'secondelement' (length=13) string 'myiterator::next' (length=16) string 'myiterator::valid' (length=17) string 'myiterator::current' (length=19) string 'myiterator::key' (length=15) int 2 string 'lastelement' (length=11) string 'myiterator::next' (length=16) string 'myiterator::valid' (length=17)
so can see: 1st, order of function(var_dump(__method__)
) output is:
string 'myiterator::rewind' (length=18) string 'myiterator::valid' (length=17) string 'myiterator::current' (length=19) string 'myiterator::key' (length=15)
2nd , 3rd, order of function output is: order of function output is:
string 'myiterator::next' (length=16) string 'myiterator::valid' (length=17) string 'myiterator::current' (length=19) string 'myiterator::key' (length=15)
4rd, order of function output is:
string 'myiterator::next' (length=16) string 'myiterator::valid' (length=17)
my question is:
- there 5 functions:
rewind();current(); key(); next(); valid();
why functions seems not execute sometimes? eg, can not seemyiterator::next
in 1st function output. ,rewind()
shows 1 time. - there 3 values in $array, supposed foreach run 3 times, can see
string 'myiterator::valid' (length=17)
appear 4 times, why?
the first part initialization of for
-loop. calls rewind
move cursor beginning of list. that's why don't see next
there.
the last part next
then, for
-loop realizes end of list reached, because valid
returned false
. valid
called 4 times, 3 times returning true
, returning false
once. how for
-loop know stop otherwise?
Comments
Post a Comment