Skip to content

Instantly share code, notes, and snippets.

@egeriis
Created October 16, 2013 14:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save egeriis/7008387 to your computer and use it in GitHub Desktop.
Save egeriis/7008387 to your computer and use it in GitHub Desktop.
An iterator example which provides a memory efficient way of handling arrays of objects.
<?php
class Trains implements Iterator
{
protected $objectIds;
private $idx = 0;
public function __construct($objectIds)
{
$this->objectIds = $objectIds;
}
public function current()
{
return new Model_Train($objectIds[$this->idx]);
}
public function rewind()
{
$this->idx = 0;
}
public function key()
{
return $this->idx;
}
public function next()
{
++$this->idx;
}
public function valid()
{
return isset($this->objectIds[$this->idx]);
}
}
$myTrains = new Trains(array(1,2,3));
foreach ($myTrains as $train)
{
// $train is Model_Train instance
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment