Home > Database > Mysql Tutorial > body text

PHP yield关键字功能与用法分析

PHPz
Release: 2019-02-12 13:09:02
Original
2347 people have browsed it

本文实例讲述了PHP yield关键字功能与用法。分享给大家供大家参考,具体如下:【推荐阅读:php入门教程

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";
}
?>
Copy after login

简单来说就是: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
…
Copy after login

示例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;
}
}
Copy after login



Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!