牛骨文教育服务平台(让学习变的简单)
博文笔记

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

创建时间:2016-07-05 投稿人: 浏览次数:226

例子:摘自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;
}
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。