是PHP Closure对象有资格进行垃圾回收 [英] Are PHP Closure Objects eligible for garbage collection

查看:115
本文介绍了是PHP Closure对象有资格进行垃圾回收的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道PHP的匿名函数是否有资格进行垃圾收集?

I was wondering if anyone knows if PHP's anonymous functions are eligible for garbage collection?

我知道用 create_function 创建的函数不是垃圾回收,但是我没有找到任何引用关于用 function(){} 语法(内部表示为Closure对象)创建的。

I know that functions created with create_function are not garbage collected but I haven't been able to find any reference about ones created with the function(){} syntax (internally represented as a Closure object).

推荐答案

PHP的垃圾回收器不区分事物类型 - 如果它至少有一个引用, 。

PHP's garbage collector does not discriminate between types of "things" - if it has at least one reference somewhere, it is kept. The moment this does not apply, the resource is garbage-collected.

这是与使用 create_function相同。 ,因为除了引用它之外,PHP还在全局作用域中引用create_function引用。一个闭包(一个Closure对象,如果你喜欢,因为这是他们是!)只存在于它创建的范围+所有传递给它的。

This is not the same as using create_function, as PHP throws the create_function reference in the global scope in addition to referencing it. A closure (a Closure object, if you prefer, as this is what they are!) only exists in the scope it was created in + all the ones you pass it to.

如果你想说服自己,运行这个小代码:

If you want to convince yourself of it, run this little piece of code:

<?php
$r = memory_get_usage();
for ($i = 0; $i < 100; $i++) {
    $k = function() {echo "boo"; };
    if (memory_get_usage() > $r) {
            echo "Different memory count. Off by: ".(memory_get_usage() -$r);
    }
    $r = memory_get_usage();
}

用create_function替换 $ k 赋值,你会得到100。

You will get exactly one echo. Replace the $k assignment with create_function, and you'll get 100.

这篇关于是PHP Closure对象有资格进行垃圾回收的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆