今天分享一个特别好用的东西,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;
结果如下
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();}
结果如下
log.txt这个文件是12M
如果你觉得还不错,给我点个赞吧!