当前位置:实例文章 » PHP实例» [文章]PHP聚合式迭代器接口IteratorAggregate用法分析

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

发布人:shili8 发布时间:2022-12-12 04:31 阅读次数:28

本文实例讲述了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程序设计有所帮助。

相关标签:

免责声明

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱290110527@qq.com删除。

其他信息

其他资源

Top