PHP YIELD使读取大文件变成可能

来源:互联网 发布:百度地图编辑软件 编辑:程序博客网 时间:2024/06/04 23:23

例子:摘自PHP手册

for the protection from the leaking of resources 

see RFC https://wiki.php.net/rfc/generators#closing_a_generator

and use finnaly

sample code

function getLines($file) {
    $f = fopen($file, 'r');
    try {
        while ($line = fgets($f)) {
            yield $line;
        }
    } finally {
        fclose($f);
    }
}

foreach (getLines("file.txt") as $n => $line) {
    if ($n > 5) break;
    echo $line;
}
0 0
原创粉丝点击