如何关闭发电机功能中的PHP资源



当我使用迭代器时如何关闭资源之后。

例如 - 如果我有这样的发电机方法:

$fileHandler = fopen($filePath, 'r');
while ($line = fgetcsv($fileHandler)) {
    yield $line;
}
fclose($fileHandler);

如何确保将调用" fclose"。

如果我调用发电机,并且只会暂停CSV的前3行,并且如果不调用下一个值" fclose",则不会被调用。

如何确保文件处理程序将关闭。

将其放入trycatchfinally块中。最后将永远被执行。

$fileHandler = fopen($filePath, 'r');
try {    
    while ($line = fgetcsv($fileHandler)) {
        yield $line;
    }
} catch(Exception $e) {
   //Do something with error.
} finally {
   fclose($fileHandler); 
}

最佳方法是像这样处理资源

if(is_resource($fileHandler)) fclose($fileHandler);

最新更新