PHP中的Iterator迭代对象属性详解

yipeiwu_com6年前PHP代码库

前言

foreach用法和之前的数组遍历是一样的,只不过这里遍历的key是属性名,value是属性值。在类外部遍历时,只能遍历到public属性的,因为其它的都是受保护的,类外部不可见。

class HardDiskDrive {

  public $brand;
  public $color;
  public $cpu;
  public $workState;

  protected $memory;
  protected $hardDisk;

  private $price;

  public function __construct($brand, $color, $cpu, $workState, $memory, $hardDisk, $price) {

    $this->brand = $brand;
    $this->color = $color;
    $this->cpu  = $cpu;
    $this->workState = $workState;
    $this->memory = $memory;
    $this->hardDisk = $hardDisk;
    $this->price = $price;
  }

}

$hardDiskDrive = new HardDiskDrive('希捷', 'silver', 'tencent', 'well', '1T', 'hard', '$456');

foreach ($hardDiskDrive as $property => $value) {

  var_dump($property, $value);
  echo '<br>';
}

输出结果为:

string(5) "brand" string(6) "希捷"
string(5) "color" string(6) "silver"
string(3) "cpu" string(7) "tencent"
string(9) "workState" string(4) "well"

通过输出结果我们也可以看得出来常规遍历是无法访问受保护的属性的。

如果我们想遍历出对象的所有属性,就需要控制foreach的行为,就需要给类对象,提供更多的功能,需要继承自Iterator的接口:

该接口,实现了foreach需要的每个操作。foreach的执行流程如下图:

看图例中,foreach中有几个关键步骤:5个。

而Iterator迭代器中所要求的实现的5个方法,就是用来帮助foreach,实现在遍历对象时的5个关键步骤:

当foreach去遍历对象时, 如果发现对象实现了Ierator接口, 则执行以上5个步骤时, 不是foreach的默认行为, 而是调用对象的对应方法即可:

示例代码:

class Team implements Iterator {

  //private $name = 'itbsl';
  //private $age = 25;
  //private $hobby = 'fishing';

  private $info = ['itbsl', 25, 'fishing'];

  public function rewind()
  {
    reset($this->info); //重置数组指针
  }

  public function valid()
  {
    //如果为null,表示没有元素,返回false
    //如果不为null,返回true

    return !is_null(key($this->info));
  }

  public function current()
  {
    return current($this->info);
  }

  public function key()
  {
    return key($this->info);
  }

  public function next()
  {
    return next($this->info);
  }

}

$team = new Team();

foreach ($team as $property => $value) {

  var_dump($property, $value);
  echo '<br>';
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对【宜配屋www.yipeiwu.com】的支持。

相关文章

合格的PHP程序员必备技能

作为PHP的爱好者,如果你想加入PHP程序的世界,一定要做好充分的准备。 如果想进入大的企业进行底层开发的话必须对互联网各方面的技术原理了解的很清楚,例如apache实现原理。语言方面既...

php中一个有意思的日期逻辑处理

今天处理了一个很小的问题。 需求是这样的,从周一到周日只能看到上周一到上周日的数据。 这里直接从数据库里根据 date 字段查询 范围即可。 但需要PHP生成 开始日期和结束日期。 最开...

深入php常用函数的使用汇总

如下所示:复制代码 代码如下:<?php//===============================时间日期===============================//...

解析php常用image图像函数集

gd_info函数:获取当前安装的GD库的信息 getimagesize函数:获取图像的大小 image_type_to_extension函数:获取图像类型的文件后缀 image_ty...

PHP中file_exists函数不支持中文名的解决方法

一般来说PHP中常使用file_exists()判断某个文件或者文件夹是否存在,如果存在则返回true,否则返回false。但是该函数在网页使用UTF8编码的情况下,对于中文的文件名或者...