回答: 生成器和迭代器是一种特殊函数和对象,可以逐个生成值,无需存储整个数据集。生成器: 生成一系列值,每次调用产生一个值;迭代器: 提供访问集合元素的方法,遍历时产生一个元素;实战: 用于分页,逐页生成数据集,无需将整个数据集存储在内存中。

PHP高级特性:生成器与迭代器的妙用
生成器
生成器是一个用来生成一系列值的特殊函数。与常规函数不同,生成器可以在每次调用时生成一个值,而无需将整个值数组存储在内存中。
立即学习“PHP免费学习笔记(深入)”;
function numbersGenerator() {
for ($i = 1; $i <= 10; $i++) {
yield $i;
}
}
foreach (numbersGenerator() as $number) {
echo $number . "\n";
}迭代器
迭代器是一种对象,提供了一种访问集合中元素的方法。与生成器类似,迭代器可以在遍历集合时生成一个元素,而无需将整个集合存储在内存中。
class NumberIterator implements Iterator {
private $start;
private $end;
private $current;
public function __construct($start, $end) {
$this->start = $start;
$this->end = $end;
$this->current = $start;
}
public function rewind() {
$this->current = $this->start;
}
public function current() {
return $this->current;
}
public function key() {
return $this->current;
}
public function next() {
$this->current++;
}
public function valid() {
return $this->current <= $this->end;
}
}
$iterator = new NumberIterator(1, 10);
foreach ($iterator as $number) {
echo $number . "\n";
}实战案例:分页器
生成器和迭代器非常适用于分页场景。通过使用生成器或迭代器,我们可以逐页生成数据集,而无需将整个数据集存储在内存中。
function paginate($query, $pageSize) {
$page = 1;
while (true) {
$offset = ($page - 1) * $pageSize;
$results = $query->offset($offset)->limit($pageSize)->execute();
if (count($results) === 0) {
break;
}
yield $results;
$page++;
}
}
foreach (paginate($query, 10) as $page) {
echo "Page $page\n";
foreach ($page as $result) {
// Process the result
}
}以上就是PHP高级特性:生成器与迭代器的妙用的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号