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 s简体繁体转换 站长工具quared 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) {
- i站长工具完美版f ($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;
- }
- }
复造代码