2019-03-12 15:44:38 2231瀏覽
今天扣丁學(xué)堂PHP培訓(xùn)老師給大家分享一篇關(guān)于yield關(guān)鍵字功能與用法分析詳解,首先yield關(guān)鍵字是php5.5版本推出的一個(gè)特性。生成器函數(shù)的核心是yield關(guān)鍵字。它最簡(jiǎn)單的調(diào)用形式看起來(lái)像一個(gè)return申明,不同之處在于普通return會(huì)返回值并終止函數(shù)的執(zhí)行,而yield會(huì)返回一個(gè)值給循環(huán)調(diào)用此生成器的代碼并且只是暫停執(zhí)行生成器函數(shù)。
<?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"; } ?>
/** * 計(jì)算平方數(shù)列 * @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; //迭代生成數(shù)組: 鍵=》值 } } } 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 ...
//對(duì)某一數(shù)組進(jìn)行加權(quán)處理 $numbers = array(‘nike‘ => 200, ‘jordan‘ => 500, ‘a(chǎn)diads‘ => 800); //通常方法,如果是百萬(wàn)級(jí)別的訪問(wèn)量,這種方法會(huì)占用極大內(nèi)存 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; } }
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】
查看更多關(guān)于“php培訓(xùn)資訊”的相關(guān)文章>>