Before you tell me to read the manual, check out the php.net documentation for this function:
Warning
This function is currently not documented; only its argument list is available.
That was helpful!
This page explains that it enables garbage collection for cyclic references. Where and when is this useful? Could someone show me an example of its use? Preferably an example where a cyclic reference is created and then collected.
gc_enable
is only needed if you call gc_disable
. There is really no sane reason to do this, as that would cause cyclic references to not be garbage collected (like pre-5.3, when the cyclic GC did not exist).
PHP's garbage collector works by reference counting. You can think of a variable as a "pointer" to an object. When an object has no pointers to it, it is "dead" because nothing can reach it, so it is garbage collected.
//one thing points to the Foo object
$a = new Foo();
//now two things do
$b = $a;
//now only $b points to it
$a = null;
//now nothing points to Foo, so php garbage collects the object
$b = null;
Consider this though:
$a = new Foo();
$b = new Bar();
$b->foo = $a;
$a->bar = $b;
$a = $b = null;
At this point nothing is holding on to $a or $b except the objects themselves. This is a cyclic reference, and in previous versions of php (< 5.3), would not be collected. The cyclic collector in 5.3 can now detect this and clean up these objects.
There is a full chapter on Garbage Collection in the PHP Manual explaining this:
I usually try not to just link offsite, but feel it's too much to summarize.
There are reasons why we use gc_disable
and gc_enable
.
In the latest PHP manual, it states
Can be very useful for big projects, when you create a lot of objects that should stay in memory. So GC can't clean them up and just wasting CPU time.
Issue in composer: https://github.com/composer/composer/pull/3482#issuecomment-65199153
Solution and people replies: https://github.com/composer/composer/commit/ac676f47f7bbc619678a29deae097b6b0710b799
Please be reminded that the second link above contains a lot of comments with graphics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With