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!
function &instance() {
static $reg;
if(!$reg) {
$reg = new Registry(); //no reference!
}
return $reg;
}
BUT
Your main trouble is that you're doing it all wrong (IMO)
You're implementing Singleton, but you're keeping references to the object (why?). You're trying to write as in C++/Java mayhap?
Make some static functions Registry::Set(), Registry::Get() and Registry::Delete() and that's it. No hassles with references, no global $registry; <span style='color:blue' title='I'm naughty, are you naughty?'>smurf</span>, no $this->reg->how->many->arrows->did->I->write->already()?
jurriemcflurrie wrote:You're right!! Sometimes I think waaayyy too difficult.
But I'm affraid that can only be done in php5? Or is there a way to get static functions in php4?
Static registries don't work in PHP4 since you can't have static properties, you can only have static functions. A halfway approach is to use a global as a container where you'd usually have a static property.
$___registry = array();
class Registry
{
function add(&$object, $name)
{
global $___registry;
$___registry[$name] =& $object;
}
function has($name)
{
global $___registry;
return array_key_exists($name, $___registry);
}
function &get($name)
{
global $___registry;
if ($this->has($name))
{
return $___registry[$name];
}
}
function delete($name)
{
global $___registry;
if ($this->has($name))
{
unset($___registry[$name]);
}
}
}
You could easily make that entire class static too since it's completely monostate anyway
The question I would have about using the Singleton pattern here is -- do you really have the problem of creating multiple instances of the Registry? I see code like this all the time where the programmer creates a single instance and passes it through the controllers without actually needing the Singleton code they implemented. I would treat the Singelton as a last resort. Most often when you only want one of an object you just simply only create one.