So, yield () is not the key to solving the problem it refers to.
That's right.
But this may allow you to mask the while() / fetch() sequence as a call to foreach() , if you prefer, without the extra memory overhead.
However, PDO is not a good example, because PDOStatement already implements a workaround interface and therefore can be repeated using foreach () :
$stmt = $pdo->query('SELECT name FROM users'); foreach ($stmt as $row) { var_export($row); }
So let's take mysqli as an example API, which can only stream results one by one.
Edit Actually, since 5.4.0 mysqli supports Traversable , so it makes no sense to use the exit with mysqli_result. But, let me keep this for a demonstration purpose.
Create such a generator
function mysqli_gen (mysqli_result $res) { while($row = mysqli_fetch_assoc($res)) { yield $row; } }
and now you can get strings using foreach with no overhead:
$res = $mysqli->query("SELECT * FROM users"); foreach (mysqli_gen($res) as $row) { var_export($row); }
Your common sense
source share