关于php的yield生成器

栏目: PHP · 发布时间: 6年前

内容简介:今天分享一个特别好用的东西,php里面的生成器(PHP 5.5.0才引入的功能),可以避免数组过大导致内存溢出的问题理解:生成器yield关键字不是返回值,他的专业术语叫产出值,只是生成一个值,并不会立即生成所有结果集,所以内存始终是一条循环的值应用场景:

今天分享一个特别好用的东西,php里面的生成器(PHP 5.5.0才引入的功能),可以避免数组过大导致内存溢出的问题

理解:生成器yield关键字不是返回值,他的专业术语叫产出值,只是生成一个值,并不会立即生成所有结果集,所以内存始终是一条循环的值

应用场景:

遍历文件目录

读取超大文件(log日志等)

下面就详细的来说一下用法

1.遍历文件目录

function glob2foreach($path, $include_dirs=false) {
    $path = rtrim($path, '/*');
    if (is_readable($path)) {
        $dh = opendir($path);
        while (($file = readdir($dh)) !== false) {
            if (substr($file, 0, 1) == '.')
                continue;
            $rfile = "{$path}/{$file}";
            if (is_dir($rfile)) {
                $sub = glob2foreach($rfile, $include_dirs);
                while ($sub->valid()) {
                    yield $sub->current();
                    $sub->next();
                }
                if ($include_dirs)
                    yield $rfile;
            } else {
                yield $rfile;
            }
        }
        closedir($dh);
    }
}

//调用

$glob = glob2foreach('D:/phpStudy/PHPTutorial/WWW');
//用于查看总共文件数量
$count = 0;
while ($glob->valid()) {
    $filename = $glob->current();
     echo $filename;
     echo "<br />";
    $count++;
    // 指向下一个,不能少
    $glob->next();
}
echo $count;

结果如下

关于 <a href='https://www.codercto.com/topics/18749.html'>php</a> 的yield生成器

2.读取超大文件

function read_file($path) {
    if ($handle = fopen($path, 'r')) {
        while (! feof($handle)) {
            yield trim(fgets($handle));
        }
        fclose($handle);
    }
}

//调用

$glob = read_file('D:/phpStudy/PHPTutorial/WWW/log.txt');
while ($glob->valid()) {
    // 当前行文本
    $line = $glob->current();
    // 逐行处理数据
     echo $line;
     echo "<br />";
    // 指向下一个,不能少
    $glob->next();
}

结果如下

关于php的yield生成器

log.txt这个文件是12M

如果你觉得还不错,给我点个赞吧!


以上所述就是小编给大家介绍的《关于php的yield生成器》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Beginning Google Maps API 3

Beginning Google Maps API 3

Gabriel Svennerberg / Apress / 2010-07-27 / $39.99

This book is about the next generation of the Google Maps API. It will provide the reader with the skills and knowledge necessary to incorporate Google Maps v3 on web pages in both desktop and mobile ......一起来看看 《Beginning Google Maps API 3》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

html转js在线工具
html转js在线工具

html转js在线工具