本文实例讲述了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程序设计有所帮助。