Answer the question
In order to leave comments, you need to log in
Where can PHP iterators come in handy?
Hello!
For several hours now I can not understand what the advantage of the classes is. I did not find a clear answer. In all the examples that I saw, a class was created that implements Iterator and it had an array property that was passed through. Why all this dance with a tambourine when there is a simple foreach? Can you please give me a normal example that will show the advantage and indispensable use of these iterators.
Thanks in advance!
Answer the question
In order to leave comments, you need to log in
Well, since we need examples, I'll come up with something ...
The task is the following. It is necessary to make requests to the API for all available pages, well, I don’t know, for example, we get articles from habr. The algorithm is as follows:
- We work until the page is the last
one - We get a list of articles and start returning them.
- As soon as they run out, we check if the current page is the last one.
And so on until the page ends.
class HabraArticles implements \IteratorAggregate
{
// ...
// Какие-то методы настроек апишки
// ...
public function getIterator(): iterable
{
$page = 0;
do {
$response = // запрос_к_апи?page=$page++
yield from $response['articles'];
} while ($response['last_page'] !== $page);
}
}
$articles = (new HabraArticles)
->какой_то_метод_настроек(23)
->ещё_какой_то_метод_настроек(42);
foreach($articles as $article) {
\var_dump($article); // Пробегаемся по всем существующим статьям и не думаем о том, как оно работает.
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question