Last active
September 23, 2016 20:42
-
-
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.
This file contains 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 | |
/** | |
* 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