当前位置: 首页 > 后端技术 > PHP

PHP遍历接口Iterator详解

时间:2023-03-29 14:52:06 PHP

从手册上查到的解释是:IteratorextendsTraversable{/*Methods*/abstractpublicmixedcurrent(void)abstractpublicscalarkey(void)abstractpublicvoidnext(void)abstractpublicvoidrewind(void)abstractpublicbooleanvalid(void)}当foreach遍历一个实现了Iterator接口的对象时,会自动调用这些方法。调用顺序是:rewind()->valid()->current()->key()->next()我们来看一下简单的代码:classmyIteratorimplementsIterator{private$position=0;private$array=array("firstelement","secondelement","lastelement",);公共函数__construct(){$this->position=0;}functionrewind(){var_dump(__METHOD__);$this->position=0;}functioncurrent(){var_dump(__METHOD__);返回$this->array[$this->position];}functionkey(){var_dump(__METHOD__);返回$this->位置;}功能下一个(){var_dump(__METHOD__);++$这个->位置;}functionvalid(){var_dump(__METHOD__);返回isset($this->array[$this->position]);}}$it=newmyIterator;foreach($itas$key=>$value){var_dump($key,$value);echo'------------------------'."\n";}以上会输出:/Users/thanatos/Web/study/blean.php:15:string'myIterator::rewind'(length=18)/Users/thanatos/Web/study/blean.php:35:string'myIterator::valid'(length=17)/Users/thanatos/Web/study/blean.php:20:string'myIterator::current'(length=19)/Users/thanatos/Web/study/blean.php:25:string'myIterator::key'(length=15)/Users/thanatos/Web/study/blean.php:43:int0/Users/thanatos/Web/study/blean.php:43:string'firstelement'(length=12)----------------------------/Users/thanatos/Web/study/blean.php:30:string'myIterator::next'(length=16)/Users/thanatos/Web/study/blean.php:35:string'myIterator::valid'(length=17)/Users/thanatos/Web/study/blean.php:20:string'myIterator::current'(length=19)/Users/thanatos/Web/study/blean.php:25:string'myIterator::key'(length=15)/Users/thanatos/Web/study/blean.php:43:int1/Users/thanatos/Web/study/blean.php:43:string'secondelement'(length=13)--------------------------/Users/thanatos/Web/study/blean.php:30:string'myIterator::next'(length=16)/Users/thanatos/Web/study/blean.php:35:string'myIterator::valid'(length=17)/Users/thanatos/Web/study/blean.php:20:string'myIterator::current'(length=19)/Users/thanatos/Web/study/blean.php:25:string'myIterator::key'(length=15)/Users/thanatos/Web/study/blean.php:43:int2/Users/thanatos/Web/study/blean.php:43:string'lastelement'(length=11)------------------------/Users/thanatos/Web/study/blean.php:30:string'myIterator::next'(length=16)/Users/thanatos/Web/study/blean.php:35:string'myIterator::valid'(length=17)