Analysis of Function and Usage of PHP Generator

  • 2021-09-16 06:20:34
  • OfStack

This paper illustrates the function and usage of PHP generator. Share it for your reference, as follows:

1. Official note: The generator provides an easier way to implement simple object iteration. Compared with the way of defining classes to implement Iterator interface, the performance overhead and complexity are greatly reduced. The generator allows you to write code in the foreach code block to iterate through 1 set of data without creating an array in memory.

2. The generator is like an ordinary custom function 1. Unlike the ordinary function which only returns once, the generator can yield as many times as needed to generate the value that needs iteration.

3. Code example:


// Generator not used 
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 the 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


/**
 *  Mass data generation example 
 * @param int $page
 * @param int $limit
 * @return Generator
 */
public function generator($page = 1,$limit = 50000)
{
  while (true) {
    echo " No. 1 {$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 " No. 1 {$page} Times ".'generator End memory: '.$this->getMemory().'<br>';
    $page++;
  }
}
    // Test generator memory consumption 
//    foreach ($this->generator() as $result) {
//      var_dump($result[0]);
//    }

For more readers interested in PHP related contents, please check the special topics of this site: "Summary of Common Functions and Skills of php", "Summary of Usage of php String (string)", "Complete Collection of Operation Skills of PHP Array (Array)", "Tutorial on Data Structure and Algorithm of PHP" and "Summary of Programming Algorithm of php"

I hope this article is helpful to everyone's PHP programming.


Related articles: