PHP iterators, PHP converters
Implements Iterator, realizing the current of Iterator (); Next (); key (); Valid (); Rewind ();
1
Php2 /*3 * Define an array first4 * Define the first position $position = 05 * Then return key and value,6 * point to Next location + + $position7 */ 8 classMyiteratorImplementsiterator{9 //define a location firstTen Private $position= 0; One Private $array; A - Public function__construct (Array $array){ - $this-Array=$array; the } - /** - * Rewind the iterator with the first element - * @return void any return value will be ignored. + */ - Public function Rewind(){ + Var_dump(__method__); A $this->position = 0; at } - /** - * Check that the current location is valid - * @return Boolean return value will be bool type Boolean, then evaluate - */ - Public functionvalid () { in Var_dump(__method__); - //determines whether the first element of an array exists to return isset($this-Array[$this-position]); + } - /** the * Returns the current element * * @return Mixed can return any type. $ */Panax Notoginseng Public function Current(){ - Var_dump(__method__); the //returns the first element of an array + return $this-Array[$this-position]; A } the /** + * Returns the key of the current element - * @return Mixed scalar succeeded, or null failed $ */ $ Public function Key(){ - Var_dump(__method__); - //returns the key of the first element of the array the return $this-position; - }Wuyi /** the * Advance to the next element - * @return void any return value will be ignored. Wu */ - Public function Next(){ About Var_dump(__method__); $++$this-position; - } - } - A $array=[ +"Firstelement", the"Secondeleent", -"Lastelement" $ ]; the the $it=NewMyiterator ($array); the foreach($it as $key=$value) { the Echo $key. ' = '.$value; - Echo"
"; in}
Execution Result:
http://www.bkjia.com/PHPjc/1072323.html www.bkjia.com true http://www.bkjia.com/PHPjc/1072323.html techarticle PHP iterator, PHP implements Iterator, implements Iterator current (); next (); key (); valid (); rewind (); 1? PHP 2/* 3 * First define an array of 4 * fixed First position $position ...