在 PHP 文档中它说:
This flexibility does come at a cost, however: generators are forward-only iterators, and cannot be rewound once iteration has started. This also means that the same generator can't be iterated over multiple times: the generator will need to either be rebuilt by calling the generator function again, or cloned via the clone keyword. Documentation
但是我尝试编写一个代码来克隆我从一个方法接收到的生成器对象,但我收到一个错误,指出生成器对象不能被克隆:
class Course {
private $students = array("avi" , "haim" , "maor" , "liran" , "yossi");
function generateStudents() {
foreach ($this->students as $student) {
yield $student;
}
}
}
$ob = new Course();
$generator = $ob->generateStudents();
// Fatal error: Trying to clone an uncloneable object of class Generator
$generator2 = clone $generator;
?>
最佳答案
According to the RFC , 生成器不能被克隆:
Generators cannot be cloned.
Support for cloning was included in the initial version, but removed in PHP 5.5 Beta 3 due to implementational difficulties, unclear semantics and no particularly convincing use cases.
看起来文档反射(reflect)了初始版本,需要更新。有一个 documentation bug提出来解决这个问题。
同样在 RFC 中,它提到了您可能不想重用生成器的原因:
Rewinding to some degree goes against the concept of generators, as they are mainly intended as one-time data sources that are not supposed to be iterated another time. On the other hand, most generators probably are rewindable and it might make sense to allow it. One could argue though that rewinding a generator is really bad practice (especially if the generator is doing some expensive calculation). Allowing it to rewind would look like it is a cheap operation, just like with arrays.
关于php - 可以克隆 PHP 生成器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22858236/