Soft references could theoretically be implemented if PHP only implemented
weak references even though the implementation would consist of a very ugly
and "coincidental" hack.

Lets say you had an object A that you wouldn't want to be collected until
approximately when PHP needs more memory. E.g. we want to implement some
sort of caching behavior. Note the difference towards weak references which
allows objects to be collected directly when they are not strongly
referenced anymore. In the caching scenario we don't know weather the object
might be used again so we want it to be retained in memory as long as it's
not a problem - e.g. as long as PHP doesn't use "too much" memory.

Now after object A is created we create a weak reference for it in our
cache. Then we create another object B which is just a StdClass with a
single field "ptr" which is a strong reference to A. Then we create a strong
reference from A to B and so a cyclic reference memory structure is born. A
(and B) will now be unable to be garbage collected until gc_collect_cycles
runs which happens when the "root buffer is full" - piggybacking on PHP's
internal approximation of when enough memory has been allocated that the
probability is high enough for garbage cycle collection to be worth it.

This also assumes that you can add an arbitrary property to the A object
without disrupting it's behavior. Adding arbitrary properties to other
objects violates encapsulation and is generally not good design. Also since
this implementation of a soft reference depends on internal PHP
implementation I would avoid such design though unless careful testing is
made and the behavior is disabled if an incremented PHP version is detected
where there is a possibility that the PHP GC implementation might have
changed.

It's interesting to think about though.

Also I would not rely on "ticks" for anything really except debugging. It's
an unreliable performance killer.

~Hannes

Reply via email to