You want to allow your objects to contain collection of items so that you can loop over them using foreach. You can do that if you implement the php iterator interface, which contains these methods.
Public function current( ) :- return the current element in your collection
Public function key( ) :- return the current key.
Public function next( ) :- return the next element.
Public function valid ( ) :- return true if the current element is valid.
Public function rewind( ) :- starts operations over from the beginning.
Phpiterator, that creates objects you can use in foreach loops. The class here is going to be called DataHandler.
It’s going to use an array internally, because array already support the methods of the iterator interface, .
First you create the DataHandler class, implementing the PHP iterator interface.
This class is going to store an array internally that you pass to its constructor, and let you iterate over that array.
<?php
class DataHandler implements Iterator
{
private $array = array( );
public function __construct($arr)
{
if(is_array($arr))
{
$this->array = $arr;
}
}
}
?>
Trending Tutorials