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
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