Preserve Singleton object

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Preserve Singleton object

Post by superdezign »

So I'm playing around with this Singleton pattern, and I ran into something that's messing me up.

I have objects that depend on Singleton pattern objects, so I define them like this:

Code: Select all

public function __construct()
{
    $this->__pObject = CObject::GetInstance();
}
However, if the instance in CObject changes, $__pObject does not. I'm considering sending the instance as a reference, but before that, I want to know if this is possible at all:

Code: Select all

private function Preserve()
{
    $this = self::$__instance;
}
I know it's not possible in the sense that I've written, but am curious as to whether or not there is a way to do this.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I'm still trying to understand why you need a singleton in the first place. Why not a registry?
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

No idea. I haven't even read into it yet. Didn't sound like it was what I was after. I'll take a look. :D

Edit:
http://pattensforphp.com wrote:[...] a Registry can replace the need to have every object you need global access to acting as a Singleton.
:D:D:D Sounds like it's exactly what I want! Thanks feyd!
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

Okay, so the registry will simplify a lot of this, but I think it still leaves me with the same problem of saving an object in the constructor, as each object may have a copy of the registry in a different state. Am I going to have to make the registry a singleton registry and access it through GetInstance() every time that I want to use it, or use a reference when passing it through constructors?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Many registries are built using statics and static calls.
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

As in static functions with a static storage object? That never even came to mind. That sounds like it'd work very nicely.
Post Reply