note 89053 modified in class.iterator by bjori
| From: | bjori@php.net | Date: | Thu, 01 Oct 2009 12:54:19 +0000 |
| Subject: | note 89053 modified in class.iterator by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-161201@lists.php.net to get a copy of this message | ||
Because the purpose of the above example is to illustrate the foreach statement's call sequence
I made my own example of the Iterator interface just to give other user's some idea of possible
solutions that might benefit from the interface.
<?php
class MysqlResult implements Iterator
{
private $result;
private $position;
private $row_data;
public function __construct ($result)
{
$this->result = $result;
$this->position = 0;
}
public function current ()
{
return $this->row_data;
}
public function key ()
{
return $this->position;
}
public function next ()
{
$this->position++;
$this->row_data = mysql_fetch_assoc($this->result);
}
public function rewind ()
{
$this->position = 0;
mysql_data_seek($this->result, 0);
/* The initial call to valid requires that data
pre-exists in $this->row_data
*/
$this->row_data = mysql_fetch_assoc($this->result);
}
public function valid ()
{
return (boolean) $this->row_data;
}
}
$link = mysql_connect("localhost", "user");
mysql_select_db('example_db', $link);
$result = new MysqlResult(mysql_query("SELECT * FROM
example_tbl"));
foreach ($result as $pos => $row) {
var_dump($pos, $row);
}
?>
--was--
Because the purpose of the above example is to illustrate the foreach statement's call sequence
I made my own example of the Iterator interface just to give other user's some idea of possible
solutions that might benefit from the interface.
<?php
class MysqlResult implements Iterator
{
private $result;
private $position;
private $row_data;
public function __construct ($result)
{
$this->result = $result;
$this->position = 0;
}
public function current ()
{
return $this->row_data;
}
public function key ()
{
return $this->position;
}
public function next ()
{
$this->position++;
$this->row_data = mysql_fetch_assoc($this->result);
}
public function rewind ()
{
$this->_position = 0;
mysql_data_seek($this->result, 0);
/* The initial call to valid requires that data
pre-exists in $this->row_data
*/
$this->row_data = mysql_fetch_assoc($this->result);
}
public function valid ()
{
return (boolean) $this->row_data;
}
}
$link = mysql_connect("localhost", "user");
mysql_select_db('example_db', $link);
$result = new MysqlResult(mysql_query("SELECT * FROM example_tbl"));
foreach ($result as $pos => $row) {
var_dump($pos, $row);
}
?>
http://php.net/manual/en/class.iterator.php