文章主要介紹了PHP yield關(guān)鍵字功能與用法,結(jié)合實(shí)例形式分析了php5.5新增的yield關(guān)鍵字功能與相關(guān)使用技巧,需要的朋友可以參考下
實(shí)例講述PHP 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ù)。
Example #1 一個(gè)簡(jiǎn)單的生成值的例子
<?phpfunctiongen_one_to_three() {for($i= 1;$i<= 3;$i++) {//注意變量$i的值在不同的yield之間是保持傳遞的。yield$i;}}$generator= gen_one_to_three();foreach($generatoras$value) {echo"$value\n";}?>
簡(jiǎn)單來(lái)說(shuō)就是:yield是僅僅是記錄迭代過(guò)程中的一個(gè)過(guò)程值
補(bǔ)充示例:
示例2:
/*** 計(jì)算平方數(shù)列* @param $start* @param $stop* @return Generator*/functionsquares($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
...
示例3:
//對(duì)某一數(shù)組進(jìn)行加權(quán)處理$numbers=array(‘nike‘ => 200, ‘jordan‘ => 500, ‘adiads‘ => 800);//通常方法,如果是百萬(wàn)級(jí)別的訪問(wèn)量,這種方法會(huì)占用極大內(nèi)存functionrand_weight($numbers){$total= 0;foreach($numbersas$number=>$weight) {$total+=$weight;$distribution[$number] =$total;}$rand= mt_rand(0,$total-1);foreach($distributionas$num=>$weight) {if($rand<$weight)return$num;}}//改用yield生成器functionmt_rand_weight($numbers) {$total= 0;foreach($numbersas$number=>$weight) {$total+=$weight;yield$number=>$total;}}functionmt_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;}}
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
- Windows7下IIS+php配置教程詳細(xì)介紹
- PHP序列化的四種實(shí)現(xiàn)方法與橫向?qū)Ρ冉坛?/a>
- PHP基于Redis消息隊(duì)列實(shí)現(xiàn)的消息推送的方法
- Linux服務(wù)器下 php7安裝redis的方法
- PHP判斷電子郵件是否正確的簡(jiǎn)單方法介紹
- 在PHP中進(jìn)行curl開(kāi)啟操作的具體教程
- PHP中間件ICE,ICE的安裝配置,ICE常見(jiàn)編譯和運(yùn)行(異常)
- win7下手動(dòng)配置apache+php+mysql記
- OneinStack一鍵PHP/JAVA/HHVM安裝及VPS手動(dòng)安裝LNMP
- PHP遭棄用!Wordpress.com開(kāi)源并轉(zhuǎn)用Javascript
分享到:
投訴收藏














