今天分享一個特別好用的東西,php裏面的生成器(PHP 5.5.0才引入的功能),能夠避免數組過大致使內存溢出的問題php
理解:生成器yield關鍵字不是返回值,他的專業術語叫產出值,只是生成一個值,並不會當即生成全部結果集,因此內存始終是一條循環的值數組
應用場景:
遍歷文件目錄
讀取超大文件(log日誌等)spa
下面就詳細的來講一下用法
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); } }
//調用code
$glob = glob2foreach('D:/phpStudy/PHPTutorial/WWW'); //用於查看總共文件數量 $count = 0; while ($glob->valid()) { $filename = $glob->current(); echo $filename; echo "<br />"; $count++; // 指向下一個,不能少 $glob->next(); } echo $count;
結果以下blog
2.讀取超大文件ip
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(); }
結果以下get
log.txt這個文件是12Mit
若是你以爲還不錯,給我點個贊吧!