本文實(shí)例講述了PHP5.5新特性之yield理解與用法。分享給大家供大家參考,具體如下:
yield生成器是php5.5之后出現(xiàn)的,yield提供了一種更容易的方法來(lái)實(shí)現(xiàn)簡(jiǎn)單的迭代對(duì)象,相比較定義類(lèi)實(shí)現(xiàn) Iterator 接口的方式,性能開(kāi)銷(xiāo)和復(fù)雜性大大降低。
yield生成器允許你 在 foreach 代碼塊中寫(xiě)代碼來(lái)迭代一組數(shù)據(jù)而不需要在內(nèi)存中創(chuàng)建一個(gè)數(shù)組。
使用示例:
/** * 計(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
...
示例2:
//對(duì)某一數(shù)組進(jìn)行加權(quán)處理 $numbers = array('nike' => 200, 'jordan' => 500, 'adiads' => 800); //通常方法,如果是百萬(wàn)級(jí)別的訪(fǎng)問(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)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《PHP數(shù)組(Array)操作技巧大全》、《PHP基本語(yǔ)法入門(mén)教程》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:安康 紹興 呼倫貝爾 金華 綏化 溫州 萊蕪 清遠(yuǎn)
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《PHP5.5新特性之yield理解與用法實(shí)例分析》,本文關(guān)鍵詞 PHP5.5,新特性,新,特性,之,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。