Suppose I'd like to build a database abstraction layer, which uses a lazy loading mechanism.
If I ask the layer to load a root object, it loads its external representation and constructs itself.
It then somehow identifies that certain linked objects exist. Since it might be costly to load all up-front, it established proxies for related objects. Such proxies should be able to get passed around.
If a first message is called on such a proxy, it loads its external representation and constructs itself. Since references to the proxy may have been passed around, the created object needs to replace the existing proxy-object in-place.
Can I in-place replace an object with another object in PHP?
I don't believe it's possible for an object to replace all references to itself with another object. Instead, have your proxy objects forward property access and method invocation using overloading. Implement proxying on a base proxy object (named e.g. OOProxy
), then extend this to a LazyProxy
class that lazily loads the proxied object. As long as you don't need to examine the type of the object, anything that has a reference to the proxy won't be able to distinguish it from the proxied.