Are PHP Closure Objects eligible for garbage collection

我们两清 提交于 2019-11-30 22:52:18

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.

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();
}

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

You can see by xdebug_debug_zval( 'a' ); if xdebug is installed. http://www.php.net/manual/en/features.gc.refcounting-basics.php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!