之前的一篇文章我们记录了PHP的迭代器(《PHP迭代器学习笔记》),今天进一步了解下PHP的生成器。
一、什么是生成器
先来看看wikipedia关于generator的定义:
In computer science, a generator is a routine that can be used to control the iteration behaviour of a loop. All generators are also iterators.[1] A generator is very similar to a function that returns an array, in that a generator has parameters, can be called, and generates a sequence of values. However, instead of building an array containing all the values and returning them all at once, a generator yields the values one at a time, which requires less memory and allows the caller to get started processing the first few values immediately. In short, a generator looks like a function but behaves like an iterator.
是不是感觉很抽象,我们先看看他在PHP中的具象呈现,然后再回头反复看看上面的定义,你可能就不会那么困惑了。
0、直观概念
生成器在PHP中直观表现是一个自定义的函数,这个函数的功能是遍历对象,往往也叫生成器函数(generator function)。
继续阅读