简体   繁体   English

使用 while 迭代生成器

[英]Iterating over generators with while

I'm writing a PDO wrapper for a new project.我正在为一个新项目编写 PDO 包装器。 A very common pattern with SQL is to write a statement such as SQL 的一个非常常见的模式是编写如下语句

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 a while loop as above.但是,如果我使用上述的while循环调用它,则无法使用这些值。 Doing a var_dump says that $row is a Generator object.做一个var_dump表示$row是一个 Generator 对象。 If I use a foreach , a var_dump shows the database data, as expected.如果我使用foreachvar_dump按预期显示数据库数据。 Is it simply not possible to traverse over generators using while , or have I confused myself here somewhere?是根本不可能使用while遍历生成器,还是我在这里的某个地方混淆了自己?

Is it simply not possible to traverse over generators using while, or have I confused myself here somewhere?是不是根本不可能使用 while 遍历生成器,还是我在这里的某个地方混淆了自己?

You have confused yourself ;) In your code sample:你把自己弄糊涂了 ;) 在你的代码示例中:

while ($row = $connection->fetch($sql)) {

You actually execute fetch() for every iteration of the loop.您实际上为循环的每次迭代执行fetch() With generators you typically use foreach() :对于生成器,您通常使用foreach()

foreach ($connection->fetch($sql) as $row) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM