Skip to content

Instantly share code, notes, and snippets.

@mannion007
Last active September 23, 2016 20:42
Show Gist options
  • Save mannion007/f5288826220584a5d1d44ba583fe0c73 to your computer and use it in GitHub Desktop.
Save mannion007/f5288826220584a5d1d44ba583fe0c73 to your computer and use it in GitHub Desktop.
Example use of IteratorAggregate interface to make a private array within the class iterable. Featuring gaming consoles because why not.
<?php
/**
* A class which contains a private list of gaming consoles.
* Can be looped as the class implements IteratorAggregate
*
* Class ConsoleCollection
*/
class ConsoleCollection implements \IteratorAggregate
{
private $consoles = [];
public function getIterator()
{
return new ArrayIterator($this->consoles);
}
public function addConsole($console)
{
$this->consoles[] = $console;
}
public function getConsole($key)
{
if(isset($this->consoles[$key])) {
return $this->consoles[$key];
}
return null;
}
}
/**
* Create a list of gaming consoles then loop it.
*/
$myCollection = new ConsoleCollection;
$myCollection->addConsole('Nintendo 64');
$myCollection->addConsole('Playstation 2');
$myCollection->addConsole('Neo Geo');
foreach ($myCollection as $console) {
echo $console . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment