×

# PHP关键字之01 - yield

Generator类

``````function squares(\$start, \$stop) {
if (\$start < \$stop) {
for(\$i = \$start; \$i <= \$stop; \$i++){
yield \$i => \$i * \$i;
}
} else {
for(\$i = \$stop; \$i <= \$start; \$i++){
yield \$i => \$i * \$i;
}
}

}

var_dump(squares(1,5));

foreach(squares(1,5) as \$k => \$v){
printf("%d squared is %d\n",\$k,\$v);
}
``````

``````object(Generator)#1 (0) {
}
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
``````

``````function xrange(\$start, \$limit, \$step = 1) {
if (\$start < \$limit) {
if (\$step <= 0) {
throw new LogicException('Step must be +ve');
}

for (\$i = \$start; \$i <= \$limit; \$i += \$step) {
yield \$i;
}
} else {
if (\$step >= 0) {
throw new LogicException('Step must be -ve');
}

for (\$i = \$start; \$i >= \$limit; \$i += \$step) {
yield \$i;
}
}
}
``````

``````echo 'Single digit odd numbers from range():  ';
foreach (range(1, 9, 2) as \$number) {
echo "\$number ";
}
echo "\n";

echo 'Single digit odd numbers from xrange(): ';
foreach (xrange(1, 9, 2) as \$number) {
echo "\$number ";
}
``````

yield 的应用场景，一般多用于循环体，比如数据库的 fetch 操作，这样可以减少内存的消耗，ZanPHP 框架就大量的这样使用。

• 《PHP经典实例》 David Sklar & Adam Trachtenberg

phper