您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息
免费发信息

PHP的迭代器接口Iterator如何使用

2024/4/20 1:54:48发布7次查看
这次给大家带来php的迭代器接口iterator如何使用,php迭代器接口iterator使用的注意事项有哪些,下面就是实战案例,一起来看一下。
本文实例讲述了php迭代器接口iterator用法。分享给大家供大家参考,具体如下:
php iterator接口的作用是允许对象以自己的方式迭代内部的数据,从而使它可以被循环访问,iterator接口摘要如下:
iterator extends traversable {   //返回当前索引游标指向的元素   abstract public mixed current ( void )   //返回当前索引游标指向的键   abstract public scalar key ( void )   //移动当前索引游标到下一元素   abstract public void next ( void )   //重置索引游标   abstract public void rewind ( void )   //判断当前索引游标指向的元素是否有效   abstract public boolean valid ( void ) }
下面是一个简单的例子演示iterator的使用方法:
<?php /** * 该类允许外部迭代自己内部私有属性$_test,并演示迭代过程 * * @author 疯狂老司机 */ class testiterator implements iterator { /* * 定义要进行迭代的数组 */ private $_test = array('dog', 'cat', 'pig'); /* * 索引游标 */ private $_key = 0; /* * 执行步骤 */ private $_step = 0; /** * 将索引游标指向初始位置 * * @see testiterator::rewind() */ public function rewind() { echo '第'.++$this->_step.'步:执行 '.method.'<br>';     $this->_key = 0;   }   /**    * 判断当前索引游标指向的元素是否设置    *    * @see testiterator::valid()    * @return bool    */   public function valid() {     echo '第'.++$this->_step.'步:执行 '.method.'<br>';     return isset($this->_test[$this->_key]);   }   /**    * 将当前索引指向下一位置    *    * @see testiterator::next()    */   public function next() {     echo '第'.++$this->_step.'步:执行 '.method.'<br>';     $this->_key++;   }   /**    * 返回当前索引游标指向的元素的值    *    * @see testiterator::current()    * @return value    */   public function current() {     echo '第'.++$this->_step.'步:执行 '.method.'<br>';     return $this->_test[$this->_key];   }   /**    * 返回当前索引值    *    * @return key    * @see testiterator::key()    */   public function key() {     echo '第'.++$this->_step.'步:执行 '.method.'<br>';     return $this->_key;   } } $iterator = new testiterator(); foreach($iterator as $key => $value){   echo 输出索引为{$key}的元素.:$value.'<br><br>'; } ?>
以上例子将输出:
第1步:执行 testiterator::rewind 第2步:执行 testiterator::valid 第3步:执行 testiterator::current 第4步:执行 testiterator::key 输出索引为0的元素:dog 第5步:执行 testiterator::next 第6步:执行 testiterator::valid 第7步:执行 testiterator::current 第8步:执行 testiterator::key 输出索引为1的元素:cat 第9步:执行 testiterator::next 第10步:执行 testiterator::valid 第11步:执行 testiterator::current 第12步:执行 testiterator::key 输出索引为2的元素:pig 第13步:执行 testiterator::next 第14步:执行 testiterator::valid
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
php怎么移除数组中的空值或者空元素
php实现一个日志功能
以上就是php的迭代器接口iterator如何使用的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录