Created
July 29, 2013 10:14
-
-
Save hakre/6103383 to your computer and use it in GitHub Desktop.
Advanced PHP Interface Example: Traversable and Countable extended
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 | |
/** | |
* Advanced PHP Interface Example: Traversable and Countable extended | |
* | |
* As Traversable is an internal interface but PHP interfaces allow to extend | |
* from multiple interfaces, it is possible to create your own internal | |
* type (here based on Traversable) and base another non-internal sub-type | |
* on it (here based on IteratorAggregate). | |
* | |
* @link http://wpkrauts.com/2013/how-to-build-flexible-php-interfaces/ | |
* @link https://eval.in/39494 | |
*/ | |
interface CountableTraversable | |
extends Traversable, Countable | |
{ | |
} | |
interface CountableTraversableAggregate | |
extends CountableTraversable, IteratorAggregate | |
{ | |
} | |
class Widgets implements CountableTraversableAggregate | |
{ | |
private $widgets = array('Blue', 'Red'); | |
function getIterator() | |
{ | |
return new ArrayIterator($this->widgets); | |
} | |
function count() | |
{ | |
return count($this->widgets); | |
} | |
} | |
$widgets = new Widgets(); | |
printf("You have %d widgets:\n", count($widgets)); | |
foreach($widgets as $key => $widget) { | |
printf("[%s]: %s\n", $key, $widget); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Another option to loop through the array would be to use the Iterator methods directly:
which , in theory, should scale better memory wise with increasing size of the looped array. Also it's good habit to actually
rewind()
an Iterator before a loop as it could be stuck somewhere in the middle from a previous, interrupted loop.