Toaster
Toaster

Reputation: 1971

Define a Custom Iterator in PHP 5.4.x?

Does PHP (5.4.x) allow one to create custom iterators that can be dropped into foreach loops? (I have seen an iterator example that was fairly clunky)

I am accessing a web API that only allows one to pull N rows/objects per call, which results in clunky local code - i.e. an outer loop for grabbing a batch of data from the API and an inner loop for processing the elements of each batch.

I would prefer to push the outer loop into an iterator (that pulls down blocks of data and keeps track of the index into the external API etc) so I can write code more like this:

$datastream = new ApiIterator(/*params here*/);
foreach($datastream as $row){
   // do inner loop processing here
}

Thanks!

Upvotes: 2

Views: 1023

Answers (1)

Ivan Yonkov
Ivan Yonkov

Reputation: 7034

It is possible from PHP 5.0, you need to use the PHP's Class Iterator interface ( http://php.net/manual/en/class.iterator.php ) and extend it (implement) in your ApiIterator Class

Upvotes: 1

Related Questions