douzhi9395 2013-02-03 09:41
浏览 43
已采纳

如果我实现一个Iterator类来封装PDOStatement,key()方法应该怎么做

I developed a interface and class to shield the PDOStatement.

The interface:

interface ResultSetInterface extends Iterator
{
    public function count();
    public function all();
}

The class:

class ResultSet implements ResultSetInterface
{
    /**
     * @var PDOStatement
     */
    protected $pdoStatement;

    protected $cursor = 0;

    protected $current = null;

    private $count = null;

    public function __construct($pdoStatement)
    {
        $this->pdoStatement= $pdoStatement;
        $this->count = $this->pdoStatement->rowCount();
    }

    public function rewind()
    {
        if ($this->cursor > 0) {
            throw new Exception('Rewind is not possible');
        }
        $this->next();
    }

    public function valid()
    {
        return $this->cursor <= $this->count;
    }

    public function next()
    {
        $this->current = $this->pdoStatement->fetch();
        $this->cursor++;
    }

    public function current()
    {
        return $this->current;
    }

    public function key()
    {
    }

    public function count()
    {
        return $this->count;
    }

    public function all() {
        $this->cursor = $this->count();
        return $this->pdoStatement->fetchAll();
    }
}

This works fine. But I'm not sure how to use the key() method which is necessary to implement an Iterator class. Any ideas?

  • 写回答

1条回答 默认 最新

  • dongshi3361 2013-02-03 10:02
    关注

    First of all, about your interface, I think it would be better for you to extend CountableIterator as you want to add the count()method and there is a magical interface for that purpose in SPL.

    About the key method. You have to remember in PHP every iterable content is an association of a key and a value. It is inherited from PHP arrays.

    Iterator is a way to overload the foreachoperator and as foreach as a sythax which is composed as foreach($iterator as $key=>$value) you have to give the key method implementation.

    In your case you have two solutions :

    • using the $pdo->cursor
    • create your own attribute called $currentKey and increment it each time you use nextmethod.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线