我開發了一個接口和類來屏蔽PDOStatement。如果我實現了一個Iterator類來封裝一個PDOStatement,key()方法應該做什麼
接口:
interface ResultSetInterface extends Iterator
{
public function count();
public function all();
}
類:
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();
}
}
這工作得很好。但我不知道如何使用實現Iterator類所需的key()方法。有任何想法嗎?
'return $ this-> cursor;'? –
謝謝,關鍵會用在什麼時候? –
http://php.net/manual/en/class.iterator.php這裏的第一個例子顯示了每個函數何時被使用。 –