PHP5.5新特性之yield PHP5.5新特性之yield理解与用法实例分析
moliyiran 人气:0本文实例讲述了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程序设计有所帮助。
加载全部内容