码迷,mamicode.com
首页 > 其他好文 > 详细

迭代器模式

时间:2017-10-29 18:35:57      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:rom   his   money   ret   for   res   time   row   div   

迭代器模式


提供单一标准接口循环或迭代任何类型的可计数数据.

示例:
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>";
}

  

迭代器模式

标签:rom   his   money   ret   for   res   time   row   div   

原文地址:http://www.cnblogs.com/itfenqing/p/7750611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!