Jeremiah
Jeremiah

Reputation: 751

php singleton per object with distinct identifier

This is something I was thinking about the other day.

I want to have a singleton-like object. Instead of a single instance of a class, I want to have a single object with a matching variable.

For instance.

an existing employee object has a employee_id = 100 the getEmployee static method is called with employee_id = 100, i want to return the already existing object with the matching employee_id or create it if it does not exist.

can this be done?

Thanks

Upvotes: 2

Views: 173

Answers (1)

jeffff
jeffff

Reputation: 1319

As in, a singleton with an array of singletons? I'm sure it can be done, maybe something similar to this in your class:

 public static function getInstance($id) {                                                               
     if (self::$_instances[$id] == null) {
        self::$_instances[$id] = new self;
     }
     return self::$_instance[$id];
 }

Of course that'd need modification to actually fetch your item, etc, and I didn't test it, but just a thought...

Upvotes: 5

Related Questions