例項講述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程式設計有所幫助。