這篇文章主要介紹了PHP5.5新特性之yield理解與用法,結(jié)合實(shí)例形式分析了php5.5 yield生成器功能、原理、使用方法及相關(guān)操作注意事項(xiàng),需要的朋友可以參考下
本文實(shí)例講述了PHP5.5新特性之yield理解與用法。分享給大家供大家參考,具體如下:
yield生成器是php5.5之后出現(xiàn)的,yield提供了一種更容易的方法來實(shí)現(xiàn)簡(jiǎn)單的迭代對(duì)象,相比較定義類實(shí)現(xiàn) Iterator 接口的方式,性能開銷和復(fù)雜性大大降低。
yield生成器允許你 在 foreach 代碼塊中寫代碼來迭代一組數(shù)據(jù)而不需要在內(nèi)存中創(chuàng)建一個(gè)數(shù)組。
使用示例:
07 | function squares( $start , $stop ) { |
09 | for ( $i = $start ; $i <= $stop ; $i ++) { |
14 | for ( $i = $start ; $i >= $stop ; $i --) { |
19 | foreach (squares(3, 15) as $n => $square ) { |
20 | echo $n . 'squared is' . $square . '<br>' ; |
輸出:
3 squared is 9
4 squared is 16
5 squared is 25
...
示例2:
02 | $numbers = array ( 'nike' => 200, 'jordan' => 500, 'adiads' => 800); |
04 | function rand_weight( $numbers ) |
07 | foreach ( $numbers as $number => $weight ) { |
09 | $distribution [ $number ] = $total ; |
11 | $rand = mt_rand(0, $total -1); |
12 | foreach ( $distribution as $num => $weight ) { |
13 | if ( $rand < $weight ) return $num ; |
17 | function mt_rand_weight( $numbers ) { |
19 | foreach ( $numbers as $number => $weight ) { |
21 | yield $number => $total ; |
24 | function mt_rand_generator( $numbers ) |
26 | $total = array_sum ( $numbers ); |
27 | $rand = mt_rand(0, $total -1); |
28 | foreach (mt_rand_weight( $numbers ) as $num => $weight ) { |
29 | if ( $rand < $weight ) return $num ; |
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。