提供了一种方法顺序访问一个聚合对象中各个元素,而又不暴露该对象的内部表示.

适用场景:
当你需要访问一个聚合对象,而这个对象不论是什么,你都需要遍历的时候,就用迭代器.

UML:

示例代码:

class User
{
private $name,$regTime,$money; public function __construct($name, $regTime)
{
$this->name = $name;
$this->regTime = $regTime;
} public function setMoney($money)
{
$this->money = $money;
} public function __toString()
{
return "{$this->name} : {$this->regTime} : {$this->money}";
}
} class UserIterator implements Iterator
{
private $users = array();
private $valid = false; public function __construct()
{
try{
$sql = "SELECT * FROM yx_users";
$pdo = new PDO('mysql:host=localhost;dbname=db_zuiyouxin', 'root', 'root');
$res = $pdo->query($sql); foreach ($res as $row) {
$user = new User($row['name'], $row['created_at']);
$user->setMoney($row['money']);
$this->users[$row['id']] = $user;
} $pdo = null;
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
} public function current()
{
return current($this->users);
} public function next()
{
$this->valid = (next($this->users) === false) ? false : true;
} public function key()
{
return key($this->users);
} public function valid()
{
return $this->valid;
} public function rewind()
{
$this->valid = (reset($this->users) === false) ? false : true;
} } $users = new UserIterator(); foreach ($users as $key => $val) {
echo $key;
echo $val;
echo "<br>";
}

  

最新文章

  1. java占位符应用
  2. spring.net 框架分析(三)ContextRegistry.GetContext()
  3. 对于JVM内存配置参数
  4. tomcat 解析(五)-Tomcat的核心组成和启动过程
  5. 多线程访问winform控件出现异常的解决方法
  6. MySQL中字符串函数详细介绍
  7. position:relative可以默认提升元素的z-index;
  8. 转:Java compiler level does not match the version of the installed Java project facet
  9. java中创建多线程两种方式以及实现接口的优点
  10. MySQL中的replace语句
  11. Ambari自定义Service
  12. loadrunner使用https请求
  13. jquery $().each,$.each的区别
  14. 几个js 拓扑图库
  15. SQL Server等待
  16. 基于Socket网络编程
  17. 创建springboot的聚合工程(三)
  18. 四条命令快速在Ubuntu16.04上配置DNS服务器
  19. C#面向服务编程技术WCF从入门到实战演练
  20. NIO - 三大组件

热门文章

  1. javascript中模仿块级作用域
  2. C# for Hbase 实现详解
  3. HUST-1350 Trie
  4. django学习随笔:execute_from_command_line
  5. NetBeans中从实体创建Restful webservice工程
  6. php split 和 explode 的区别
  7. CSS中的层叠、特殊性、继承、样式表中的@import
  8. n2n搭建手记-1-V1
  9. [BZOJ4896][THUSC2016]补退选(Trie)
  10. UVA 1514 Piece it together (二分图匹配)