当前位置: 移动技术网 > IT编程>开发语言>PHP > PHP聚合式迭代器接口IteratorAggregate用法分析

PHP聚合式迭代器接口IteratorAggregate用法分析

2018年01月26日  | 移动技术网IT编程  | 我要评论

撕开她的衣服,无糖糖浆,richic

本文实例讲述了php聚合式迭代器接口iteratoraggregate用法。分享给大家供大家参考,具体如下:

php iteratoraggregate又叫聚合式迭代器,它提供了创建外部迭代器的接口,接口摘要如下:

iteratoraggregate extends traversable {
  abstract public traversable getiterator ( void )
}

实现getiterator方法时必须返回一个实现了iterator接口的类的实例。

例子说明:

<?php
/**
 * 利用聚合式迭代器,并返回一个实现了iterator接口的类的实例
 *
 * @author 疯狂老司机
 */
class mydata implements iteratoraggregate {
  public $one = "public property one";
  public $two = "public property two";
  public $three = "public property three";
  public function __construct() {
    $this->last = "last property";
  }
  public function getiterator() {
    return new arrayiterator($this);
  }
}
$obj = new mydata;
foreach($obj as $key => $value) {
  var_dump($key, $value);
  echo '<br>';// linux:echo "\n";
}
?>

以上例子输出:

string 'one' (length=3)
string 'public property one' (length=19)
string 'two' (length=3)
string 'public property two' (length=19)
string 'three' (length=5)
string 'public property three' (length=21)
string 'last' (length=4)
string 'last property' (length=13)

arrayiterator迭代器会把对象或数组封装为一个可以通过foreach来操作的类,具体可参考spl 迭代器相关介绍,感兴趣的朋友可参考本站。

更多关于php相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《php数组(array)操作技巧大全》、《php基本语法入门教程》、《php运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网