I want to implement a class, which caches some internal results. These results are the same for all instances of the class, i.e. it might be wise to share this cache among all instances.
However, these results may be different for sub-classes, i.e. the cache shall not be shared with sub-classes. Since the cache is a good idea for all sub-classes as well, the mechanism shall be inherited nevertheless. But each sub-class has to use a different static array.
I can think of various hacks and complicated patterns to attain this goal, but none looks really sane. Does anybody know of an efficient pattern in PHP?
A combination of a
private staticvariable to hold the cached data for all subclasses andprotectedaccessor functions sounds like it would work, and it’s not too complicated:Taking it from here, you can get fancy so that accessing the cache is very convenient at the price of becoming somewhat evil:
You would then be able to use this like
See it in action.