tags:

views:

54

answers:

1

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

+4  A: 

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...

pssdbt
I'll give it a try.
Jeremiah
Any reason you used $_instance instead of $instance, if that a standard for singleton or static objects?
Jeremiah
Works like a charm. Thanks
Jeremiah
@Jeremiah, a preceding underscore is just a common convention to indicate that the $_instance variable has a private scope. See http://pear.php.net/manual/en/standards.naming.php
Mark