PHP 中的垃圾回收是如何工作的?即,局部函数变量如何清理?
如果我为函数内未声明为全局的变量分配一个值,该变量会在函数终止时自动取消设置还是仅在 PHP 脚本执行完毕时才会取消设置?
我试图确定手动取消设置函数内的临时函数作用域变量是否更明智,或者不用担心,因为它们将被 PHP 引擎自动取消设置。
If I assign a value to variable that is not declared global inside a function will that variable be unset automatically when function terminates or will it only be unset when the PHP script finishes executing?
I'm trying to determine if it's smarter to unset temporary, function scope variables within the function manually or to not worry about because they will be automatically unset by the PHP engine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当函数退出时,该变量将被取消设置,除非它具有对其保持“活动”状态的外部引用。变量实际占用的内存是否被释放完全取决于垃圾收集器。 GC 是一个昂贵的操作,PHP 只会在需要时调用它(例如内存紧张)。
The variable will be unset when the function exits, unless it has external references to it which would keep it "alive". Whether the actual memory the variable occupied is freed or not is entirely up to the garbage collector. GC is an expensive operation, and PHP will only invoke it when needed (e.g. memory's getting tight).
这完全取决于函数的范围。从理论上讲,您可以让整个脚本在一个函数的范围内运行(希望该函数调用其他函数,但仍然......)。
对于具有最小副作用的合理大小的函数,保留对象设置是完全可以的——它们的析构函数将在函数完成时被调用(这是未设置的第二个效果),并且它们将在第一个过程中被清理函数完成后的清理周期。对于涉及创建大量对象的较大函数,最好手动删除对象。
That entirely depends on the scope of the function. Theoretically, you could have your entire script run within the scope of one function (hopefully one that calls other functions, but still...).
For a reasonably sized function with minimal side-effects, it is perfectly fine to leave your objects set -- their destructors will be called upon completion of the function (that is the second effect of unset) and they will be cleaned up during the first cleanup cycle after the function is complete. For a larger function which involves the creation on a large number of objects, then it might be better to manually remove the objects.
Zend 引擎将为您进行清理工作,
根据需要减少引用计数。The Zend Engine will do the cleanup for you,
decrementing reference counts as needed.