Cyclic Garbage Collection
Enter something called a cyclic garbage collector.Basically, this is a function which will try to detect those circular references. We call it cyclic, because it’s generalized to not just handle circular references, but handle any kind of Cycle.
So how does it work?
Collecting Cycles
I’m going to describe this backwards. I’m going to talk about how it identifies roots later. From here, let’s talk about how it processes those roots to collect free memory.PHP has a list a linked-list of possible “roots”. These are values that have had their refcount decremented and hence could be part of a cycle.Internally, the collector uses a “color code” system to identify states for specific values.Black – A normal variable, nothing specialPurple – A normal variable, but has been marked as a “possible root”, meaning that it may be part of a cycle that’s no longer reachableGrey – In process variable, nothing specialWhite – In process variable, but can be freed.They are nothing more than bit flags, but the color system is “easier” to understand.