Created
August 7, 2013 13:19
-
-
Save horitaku1124/6173956 to your computer and use it in GitHub Desktop.
PDOのセレクト結果をForeachで回すためのイテレータ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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