php - 可以克隆 PHP 生成器吗?

标签 php oop clone generator

在 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/

相关文章:

php - MySQL 从多个表中删除行

java - 观察者模式 vs 事件总线消息方法

c++ - 类型为 "const char *"的值不能分配给类型为 "char"的实体 C OOP

PHP 解析目录和子目录的文件路径和仅 jpg 图片类型的名称

php - Laravel 5 表单请求验证返回禁止错误

java - 在 Java 中克隆一个对象需要什么

c# - 使用 MemberwiseClone 实现撤销/重做

c# - 在 C# 中使用 Moq 对克隆方法进行单元测试

javascript - 从数据库加载预选值以进行选择

java - 为什么 java.lang.String 是大写的?