php - PHP 生成器函数未执行

标签 php generator fgets yield

在下面的代码中,我的输出没有得到“处理”。我看到文件句柄是一个资源,文件在调用 FqReader 的构造函数时打开,我检查了所有这些。但执行 FqReader::getread() 时,我看不到输出,并且返回的数组为空。当我使用 while(1) 而不是现在代码中的逻辑测试时,第一个 while 循环也不会被执行。

<?php

class FastqFile {
    function __construct($filename) {
        if (substr($filename, -3, 3) == '.gz') {
            $this->handle = gzopen($filename, 'r');
            return $this->handle;
        }
        else
            $this->handle = fopen($filename, 'r');
            return $this->handle;
    }
}

class FqReader {
    function __construct($file_handle) {
        $this->handle = $file_handle;
    }
    function getread() {
        while ($header = fgets($this->handle) !== false) {
            echo "handled";
            $bases = fgets($this->handle);
            $plus = fgets($this->handle);
            $scores = fgets($this->handle);
            yield array($header, $plus, $scores);
        }
    }
}

$filename = $argv[1];
$file_handle = new FastqFile($filename);
var_dump($file_handle);
$reader = new FqReader($file_handle);
var_dump($reader->getread());

它输出:

object(FastqFile)#1 (1) {
  ["handle"]=>
  resource(5) of type (stream)
}
object(Generator)#3 (0) {
}

最佳答案

$file_handle 是一个 FastqFile 实例。然后将该对象传递给 fgets(),但需要将该对象的句柄传递给 fgets()。例如:

class FqReader {
    function __construct($file_handle) {
        $this->handle = $file_handle->handle;
    }
    function getread() {
        while ($header = fgets($this->handle) !== false) {
            echo "handled";
            $bases = fgets($this->handle);
            $plus = fgets($this->handle);
            $scores = fgets($this->handle);
            yield array($header, $plus, $scores);
        }
    }
}

使用 yield 并没有向您显示该错误。

关于php - PHP 生成器函数未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45895755/

相关文章:

php - 我可以使用 header() 来传递查询字符串参数吗?

PHP 在登录时从特定用户获取特定数据

python - 是否有一种内置方法可以将无参数函数转换为生成器?

python - 加速 for 循环,也许使用生成器?

c - 从 stdin 获取输入的问题 - 来自 valgrind 的读/写无效

php - 从 php/mysql 插入中删除\

php - Laravel - 迁移,表结构修改 - 正确方法

python - 使用生成器表达式时如何从字典列表中获取项目的键

c - fgets 函数未读取输入中的第一个字符

c - 如何确定使用 fgets() 读取的字符数?