前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >PHP预定义接口——Iterator用法示例

PHP预定义接口——Iterator用法示例

作者头像
砸漏
发布2020-11-02 14:31:59
5960
发布2020-11-02 14:31:59
举报
文章被收录于专栏:恩蓝脚本

本文实例讲述了PHP预定义接口——Iterator用法。分享给大家供大家参考,具体如下:

Iterator(迭代器)接口

可在内部迭代自己的外部迭代器或类的接口。

接口摘要

代码语言:javascript
复制
Iterator extends Traversable {
    /* 方法 */
    abstract public current ( void ) : mixed
    abstract public key ( void ) : scalar
    abstract public next ( void ) : void
    abstract public rewind ( void ) : void
    abstract public valid ( void ) : bool
}

例:

代码语言:javascript
复制
<?php
class myIterator implements Iterator
{
  private $position = 0;
  private $array = array(
    'first_element',
    'second_element',
    'last_element',
  );

  /**
   * 重置键的位置
   */
  public function rewind(): void
  {
    var_dump(__METHOD__);
    $this- position = 0;
  }

  /**
   * 返回当前元素
   */
  public function current()
  {
    var_dump(__METHOD__);
    return $this- array[$this- position];
  }

  /**
   * 返回当前元素的键
   * @return int
   */
  public function key(): int
  {
    var_dump(__METHOD__);
    return $this- position;
  }

  /**
   * 将键移动到下一位
   */
  public function next(): void
  {
    var_dump(__METHOD__);
    ++$this- position;
  }

  /**
   * 判断键所在位置的元素是否存在
   * @return bool
   */
  public function valid(): bool
  {
    var_dump(__METHOD__);
    return isset($this- array[$this- position]);
  }
}

$it = new myIterator;

foreach ($it as $key =  $value) {
  var_dump($key, $value);
  echo "\n";
}

输出结果:

string ‘myIterator::rewind’ (length=18) string ‘myIterator::valid’ (length=17) string ‘myIterator::current’ (length=19) string ‘myIterator::key’ (length=15) int 0 string ‘first_element’ (length=13) string ‘myIterator::next’ (length=16) string ‘myIterator::valid’ (length=17) string ‘myIterator::current’ (length=19) string ‘myIterator::key’ (length=15) int 1 string ‘second_element’ (length=14) string ‘myIterator::next’ (length=16) string ‘myIterator::valid’ (length=17) string ‘myIterator::current’ (length=19) string ‘myIterator::key’ (length=15) int 2 string ‘last_element’ (length=12) string ‘myIterator::next’ (length=16) string ‘myIterator::valid’ (length=17)

由结果可知,当类实现了Iterator接口,实现改类实例数据集的时候首先会将数据集的键重置,然后逐步后移,每次都会进行然后返回当前元素以及当前键。

希望本文所述对大家PHP程序设计有所帮助。

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020-09-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Iterator(迭代器)接口
  • 接口摘要
  • 例:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档