源码论坛,商业源码下载,尽在锦尚中国商业源码论坛
标题:
PHP yield关键字功能与用法分析
[打印本页]
作者:
欧阳锋
时间:
2019-1-20 18:29
标题:
PHP yield关键字功能与用法分析
本文实例讲述了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;
}
}
复制代码
欢迎光临 源码论坛,商业源码下载,尽在锦尚中国商业源码论坛 (https://bbs.52jscn.com/)
Powered by Discuz! X3.3