php - Iterating over generators with while
I'm writing a PDO wrapper for a new project. A very common pattern with SQL is to write a statement such as
while ($row = $connection->fetch($sql)) {
...
}
My wrapper function is essentially this:
public function fetch($query, $bindings)
{
$stmt = $this->getPdo()->prepare($query);
$stmt->execute($bindings);
$stmt->setFetchMode($this->getFetchMode());
foreach ($stmt as $record) {
yield $record;
}
}
But I can't use the values if I call this using awhile
loop as above. Doing avar_dump
says that$row
is a Generator object. If I use aforeach
, avar_dump
shows the database data, as expected. Is it simply not possible to traverse over generators usingwhile
, or have I confused myself here somewhere?
Answer
Solution:
You have confused yourself ;) In your code sample:
You actually execute
fetch()
for every iteration of the loop. With generators you typically useforeach()
: