服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - PHP教程 - PHP中的Iterator迭代对象属性详解

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

2021-08-01 14:42itbsl PHP教程

这篇文章主要给大家介绍了关于PHP中Iterator迭代对象属性的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用PHP具有一定的参考学习价值,需要的朋友们下面来一起学习学习吧

前言

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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的执行流程如下图:

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

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

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

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

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

示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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>';
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。

原文链接:https://www.cnblogs.com/itbsl/p/10690133.html

延伸 · 阅读

精彩推荐