在下面的代码中,我的输出没有得到“处理”。我看到文件句柄是一个资源,文件在调用 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/