這篇文章主要介紹了PHP5.5新特性之yield理解與用法,結合實例形式分析了php5.5 yield生成器功能、原理、使用方法及相關操作注意事項,需要的朋友可以參考下
本文實例講述了PHP5.5新特性之yield理解與用法。分享給大家供大家參考,具體如下:
yield生成器是php5.5之後出現的,yield提供了一種更容易的方法來實現簡單的迭代對象,相比較定義類實現 Iterator 接口的方式,性能開銷和複雜性大大降低。
yield生成器允許你 在 foreach 代碼塊中寫代碼來迭代一組數據而不需要在內存中創建一個數組。
使用示例:
/** * 計算平方數列 * @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; //迭代生成數組: 鍵=》值 } } } foreach (squares(3, 15) as $n => $square) { echo $n . 'squared is' . $square . '<br>'; }
輸出:
3 squared is 9
4 squared is 16
5 squared is 25
...
示例2:
//對某一數組進行加權處理 $numbers = array('nike' => 200, 'jordan' => 500, 'adiads' => 800); //通常方法,如果是百萬級別的訪問量,這種方法會佔用極大內存 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; } } //改用yield生成器 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; } }
更多關於PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP數組(Array)操作技巧大全》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧彙總》
希望本文所述對大家PHP程序設計有所幫助。