Skip to content

Instantly share code, notes, and snippets.

@horitaku1124
Created August 7, 2013 13:19
Show Gist options
  • Save horitaku1124/6173956 to your computer and use it in GitHub Desktop.
Save horitaku1124/6173956 to your computer and use it in GitHub Desktop.
PDOのセレクト結果をForeachで回すためのイテレータ
<?php
/**
* PDOのセレクト結果をForeachで回すためのイテレータ
*
* Class StatementIterator
* @package LIBRARY
*/
class StatementIterator implements \Iterator {
/**
* @var \PDOStatement
*/
private $stmt; //最初の数
private $index = 0; //現在位置
private $thisValue = false;
/**
* コンストラクタが呼ばれた時点で次の値を用意しておかなければいけない
*
* @param $stmt \PDOStatement
*/
public function __construct($stmt)
{
$this->stmt = $stmt;
$this->next();
}
/**
* 現在(次?)の要素を返す
*/
public function current() {
return $this->thisValue;
}
/**
* 現在の要素のキーを返す
*/
public function key() {
return $this->index;
}
/**
* 次の要素
*/
public function next() {
$this->index++;
$this->thisValue = $this->stmt->fetch(\PDO::FETCH_ASSOC);
}
/**
* 最初の要素に
* あとで考える
*/
public function rewind() {
$this->index = 0;
}
/**
* @return bool 次の要素に走査できたか
*/
public function valid() {
return $this->thisValue !== false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment