Are PHP Closure Objects eligible for garbage collection

前端 未结 2 705
忘掉有多难
忘掉有多难 2021-01-06 11:19

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

I know that functions created with create_function a

相关标签:
2条回答
  • 2021-01-06 11:54

    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.

    0 讨论(0)
  • 2021-01-06 12:05

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

    0 讨论(0)
提交回复
热议问题