Analysis of yield Understanding and Usage Examples of New Features of PHP 5.5

  • 2021-11-13 01:08:30
  • OfStack

This article illustrates the yield understanding and usage of the new features of PHP 5.5. Share it for your reference, as follows:

The yield generator emerged after php 5.5, and yield provides an easier way to implement simple iterative objects. Compared with the way of defining classes to implement Iterator interfaces, the performance overhead and complexity are greatly reduced.

The yield generator allows you to write code in the foreach code block to iterate through 1 set of data without creating an array in memory.

Use example:


/**
 *  Calculate the square sequence 
 * @param $start
 * @param $stop
 * @return Generator
 */
function squares($start, $stop) {
  if ($start < $stop) {
    for ($i = $start; $i <= $stop; $i++) {
      yield $i => $i * $i;
    }
  }
  else {
    for ($i = $start; $i >= $stop; $i--) {
      yield $i => $i * $i; // Iterative generation of arrays:   Key = "Value 
    }
  }
}
foreach (squares(3, 15) as $n => $square) {
  echo $n . 'squared is' . $square . '<br>';
}

Output:

3 squared is 9
4 squared is 16
5 squared is 25
...

Example 2:


// To a 1 The array is weighted 
$numbers = array('nike' => 200, 'jordan' => 500, 'adiads' => 800);
// The usual method, if it is a million accesses, this method will take up a lot of memory 
function rand_weight($numbers)
{
  $total = 0;
  foreach ($numbers as $number => $weight) {
    $total += $weight;
    $distribution[$number] = $total;
  }
  $rand = mt_rand(0, $total-1);
  foreach ($distribution as $num => $weight) {
    if ($rand < $weight) return $num;
  }
}
// Convert to yield Generator 
function mt_rand_weight($numbers) {
  $total = 0;
  foreach ($numbers as $number => $weight) {
    $total += $weight;
    yield $number => $total;
  }
}
function mt_rand_generator($numbers)
{
  $total = array_sum($numbers);
  $rand = mt_rand(0, $total -1);
  foreach (mt_rand_weight($numbers) as $num => $weight) {
    if ($rand < $weight) return $num;
  }
}

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

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


Related articles: