this article illustrates the function and usage of the PHP generator. Share to you for your reference, as follows:

1. official: generator provides an easier way to achieve a simple object iterative , compared to defined class implements the Iterator interface, the performance overhead and complexity is greatly reduced. The generator allows you to write code in the foreach code block to iterate a set of data without the need to create an array in memory.

2. is a common custom builder functions like , return time is different, the generator can be according to the needs of the yield times, in order to generate value iteration.

3. code example:

 / / echo 'start generator unused memory:'.getMemory (.'<); br>'; $nums = range (01000000); echo ('.getMemory) 'end memory:.'< br>'; / / output: / / 0.23M / / to the end of memory memory: 130.31. / / use generator echo ''.getMemory (.'<): memory; br>'; $nums = xrange (1000000); function xrange ($total) {for ($i = 0; $i < $total; $i++) {yield $i}}; echo 'end of memory:'.getMemory (). < br>'; / / output memory: 0.23M / / / / to the end of the 

4. memory: 0.23M application example

 / * * * * @param int $page * @param example int $limit @return Generator public function generator * * / generate large amounts of data ($page = 1, limit = $50000) {while (true) {echo "{$page}".'generator (getMemory) memory:'.$this->.'< 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; / / if generator (count ($resultAll)! = $limit) {break}; echo" {$page} ".'generator the end of memory:'.$this->.'< br> (getMemory) '; $page++;}} / / foreach / / memory consumption test generator ($this-> (generator); as $result) {/ / var_dump ($result[0]); / / 

PHP} more about the related content of interested readers can view the topic:" php With the function and techniques of "," php string (string) "PHP array (Array) technique, "PHP data structure and algorithm tutorial "and" php program the design of

algorithm summary "the hope for all PHP programming help.

you might be interested in this article:

" art_bot ">


This concludes the body part

This paper fixed link:http://www.script-home.com/analysis-of-the-function-and-usage-of-php-generator.html | Script Home | +Copy Link

Article reprint please specify:Analysis of the function and usage of PHP generator | Script Home

You may also be interested in these articles!