This time for you to bring the PHP generator how to use, the use of PHP generator considerations are what, the following is the actual case, together to see.
1. Official note: The generator provides an easier way to implement a simple object iteration, comparing the way that the definition class implements the Iterator interface, with significantly reduced performance overhead and complexity. The generator allows you to write code in a foreach code block to iterate over a set of data without having to create an array in memory.
2. The generator is just like a normal custom function, and the normal function returns only once differently, and the generator can yield multiple times as needed to generate values that need to be iterated.
3. code example:
Did not use the generator echo ' Start Memory: '. GetMemory (). ' <br> '; $nums = range (0,1000000); Echo ' End memory: '. GetMemory (). ' <br> ';//output result//start memory: 0.23m//End Memory: 130.31//use generator echo ' Start Memory: '. GetMemory (). ' <br> '; $nums = xrange (1000000), function xrange ($total) {for ($i = 0; $i < $total; $i + +) { yield $i; } }echo ' End Memory: '. GetMemory (). ' <br> ';//output result//start memory: 0.23m//End Memory: 0.23M
4. Practical Application Examples
/** * Large Data Generation example * @param int $page * @param int $limit * @return Generator */public function Generator ($page = 1, $limit = 5 0000) {While (true) { echo "{$page} times". Generator start Memory: '. $this->getmemory (). ' <br> '; $start = ($page-1) * $LIMIT; $sql = "Select P.id,p.wh_code,p.goods_sn from P_product as P WHERE p.wh_code like '%yb% ' OR p.wh_code like '%dzwh% ' LIMIT {$start},{$limit} "; $RESULTALL = db ()->fetchall ($sql); Yield $resultAll; Generator if (count ($resultAll)! = $limit) {break ; } echo "{$page} times". Generator End Memory: '. $this->getmemory (). ' <br> '; $page + +; }} Test generator memory Consumption// foreach ($this->generator () as $result) {// var_dump ($result [0]);/ }
Believe that you have read the case of this article you have mastered the method, more exciting please pay attention to the PHP Chinese network other related articles!
Recommended reading:
PHP Direct implementation to generate poster ads
Phpqrcode class generation Two-dimensional code detailed
How to get HTTP parameters in Egg.js