本文實例講述了PHP yield關鍵字功能與用法。分享給大家供大家參考,具體如下:
yield 關鍵字是php5.5版本推出的一個特性。生成器函數的核心是yield關鍵字。它最簡單的調用形式看起來像一個return申明,不同之處在于普通return會返回值并終止函數的執行,而yield會返回一個值給循環調用此生成器的代碼并且只是暫停執行生成器函數。
Example #1 一個簡單的生成值的例子
<?php function gen_one_to_three() { for ($i = 1; $i <= 3; $i++) { //注意變量$i的值在不同的yield之間是保持傳遞的。 yield $i; } } $generator = gen_one_to_three(); foreach ($generator as $value) { echo "$value\n"; } ?>
簡單來說就是:yield
是僅僅是記錄迭代過程中的一個過程值
補充示例:
示例2:
/** * 計算平方數列 * @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
...
示例3:
//對某一數組進行加權處理 $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程序設計有所幫助。