1Iteratorextendstraversable {2 /*Methods*/3 Abstract Public Mixed Current(void)4 Abstract PublicScalarKey(void)5 Abstract PublicvoidNext(void)6 Abstract PublicvoidRewind(void)7 Abstract Public Booleanvalid (void)8}
Therefore, for this question, the following answers can be made:
1 classSampleImplementsIterator2 {3 Private $_items=Array(1,2,3,4,5,6,7);4 Public function__construct () {5;//void6 }7 Public function Rewind() {Reset($this-_items); }8 Public function Current() {return Current($this-_items); }9 Public function Key() {return Key($this-_items); }Ten Public function Next() {return Next($this-_items); } One Public functionValid () {return($this- Current() !==false ); } A } - $sa=Newsample (); - foreach($sa as $key=$val){ the Print $key. "=".$val; -}
————————————————————————————————————————————
PHP5 already has the iterator interface, as long as the implementation of the interface, that is, you can implement the object private property is foreach traversal
1<?PHP2 classSampleImplementsiterator{3 Private $var=Array(1,2,3,4,5);4 Public function__construct () {}5 Public function Rewind(){Reset($this-var);}6 Public function Current(){return Current($this-var);}7 Public function Key(){return Key($this-var);}8 Public function Next(){return Next($this-var);}9 Public functionValid () {return($this- Current()!==false);}Ten } One $s=NewSample (); A foreach($s as $k=$v){Echo $k.‘ = '.$v.‘ <br/> ';} -?>
Enables an object to be a foreach loop like an array, requiring that the property be private