php5.5新增的yield關鍵字功能與相關使用技巧

LCRxxoo發表於2019-01-15
文章主要介紹了PHP yield關鍵字功能與用法,結合例項形式分析了php5.5新增的yield關鍵字功能與相關使用技巧,需要的朋友可以參考下

例項講述PHP yield關鍵字功能與用法具體如下:

yield 關鍵字是php5.5版本推出的一個特性。生成器函式的核心是yield關鍵字。它最簡單的呼叫形式看起來像一個return申明,不同之處在於普通return會返回值並終止函式的執行,而yield會返回一個值給迴圈呼叫此生成器的程式碼並且只是暫停執行生成器函式。

Example #1 一個簡單的生成值的例子

  1. <?php
  2. function gen_one_to_three() {
  3.   for ($i = 1; $i <= 3; $i++) {
  4.     //注意變數$i的值在不同的yield之間是保持傳遞的。
  5.     yield $i;
  6.   }
  7. }
  8. $generator = gen_one_to_three();
  9. foreach ($generator as $value) {
  10.   echo "$value\n";
  11. }
  12. ?>

簡單來說就是:yield是僅僅是記錄迭代過程中的一個過程值

補充示例:

示例2:

  1. /**
  2.  * 計算平方數列
  3.  * @param $start
  4.  * @param $stop
  5.  * @return Generator
  6.  */
  7. function squares($start, $stop) {
  8.   if ($start < $stop) {
  9.     for ($i = $start; $i <= $stop; $i++) {
  10.       yield $i => $i * $i;
  11.     }
  12.   }
  13.   else {
  14.     for ($i = $start; $i >= $stop; $i--) {
  15.       yield $i => $i * $i; //迭代生成陣列: 鍵=》值
  16.     }
  17.   }
  18. }
  19. foreach (squares(3, 15) as $n => $square) {
  20.   echo $n . ‘squared is‘ . $square . ‘<br>‘;
  21. }

輸出:

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

示例3:

  1. //對某一陣列進行加權處理
  2. $numbers = array(‘nike‘ => 200, ‘jordan‘ => 500, ‘adiads‘ => 800);
  3. //通常方法,如果是百萬級別的訪問量,這種方法會佔用極大記憶體
  4. function rand_weight($numbers)
  5. {
  6.   $total = 0;
  7.   foreach ($numbers as $number => $weight) {
  8.     $total += $weight;
  9.     $distribution[$number] = $total;
  10.   }
  11.   $rand = mt_rand(0, $total-1);
  12.   foreach ($distribution as $num => $weight) {
  13.     if ($rand < $weight) return $num;
  14.   }
  15. }
  16. //改用yield生成器
  17. function mt_rand_weight($numbers) {
  18.   $total = 0;
  19.   foreach ($numbers as $number => $weight) {
  20.     $total += $weight;
  21.     yield $number => $total;
  22.   }
  23. }
  24. function mt_rand_generator($numbers)
  25. {
  26.   $total = array_sum($numbers);
  27.   $rand = mt_rand(0, $total -1);
  28.   foreach (mt_rand_weight($numbers) as $num => $weight) {
  29.     if ($rand < $weight) return $num;
  30.   }
  31. }

 

希望本文所述對大家PHP程式設計有所幫助。

相關文章