doq1969 2015-12-29 14:15
浏览 21
已采纳

PHP生成器 - 垃圾收集

Simple question.

When or how, by PHP or yourself do generators destroy their stacks?

Take the following example:

function doWork(): Generator
{
    // create some objects.
    $o1 = new stdClass();
    $o2 = new stdClass();

    // pause here and wait for data.
    $value = yield 1;

    // By referencing the above objects, they shouldn't destruct.
    $o1->property = $value;
    $o2->property = $value;

    yield $o1;
    yield $o2;

    // End of stack.
}

// Create the generator.
$generator = doWork();

$value = $generator->current(); // $value will equal 1.

if ($x) {
    $generator->send('Hello, World!'); // Continue execution of the generator.
    $o1 = $generator->current();
    $generator->next();
    $o2 = $generator->current();
    $generator->next(); // Complete the generator

    var_dump($o1);
    var_dump($o2);
} else {
    // Do nothing with the generator.
}

// Carry on with script ...

In this example a generator is started and two objects are created. At this point it is yielded, and further data is requested.

An IF statement is reached.

Case 1

If $x is true, the value "Hello, World!" will be sent to the generator and the objects will be populated with their new properties.

The next time the yielded data is read, the objects will be returned.

Case 2

If $x is false, the generator will no longer be used.

Question

In case 1, I would expect the stack to close like any other function, but what happens to the generator in case 2? Does it and all of the remaining object references stay in memory until the script ends?

Or does the loss of reference to $generator cause it, and all references inside to be cleared out?

  • 写回答

1条回答 默认 最新

  • duanqian3953 2015-12-29 16:23
    关注

    There are two conditions under which a generator destroys its execution context (which also includes the variable table):

    1. If the generator finishes execution. This may either happen by executing a return (including the implicit return at the end of the function) or through an uncaught exception during execution of the generator.
    2. If all references to the generator object are relinquished.

    So, no, the generator will not live until the script ends. It will be destroyed once the $generator variable goes out of scope, at which point the generator will relinquish its references to the variable values and other execution state.

    You can easily observe destruction order by creating a class that echos in the destructor and then instantiating this class into a local variable.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 关于#java#的问题:找一份能快速看完mooc视频的代码
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码
  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题