PHP5.5新特性之yield理解与用法实例分析

yield生成器是php5.5之后出现的,yield提供了一种更容易的方法来实现简单的迭代对象,相比较定义类实现 Iterator 接口的方式,性能开销和复杂性大大降低。

yield生成器允许你 在 foreach 代码块中写代码来迭代一组数据而不需要在内存中创建一个数组。

使用示例:

/** * 计算平方数列 * @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
    ...

示例2:

//对某一数组进行加权处理 $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相关内容感兴趣的读者可查看本站专题:《php面向对象程序设计入门教程》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《PHP运算与运算符用法总结》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/56e8d1aa122ca42cdd28edb4e9374cbd.html