Page 1 of 1

Singletons and inheritance

Posted: Thu Aug 17, 2006 10:30 am
by Luke
What if I wanted to create a hierarchy of classes that basically would act a one singleton. For example... I have an http_response class. It has a child called front_http_response which is used by my front controller to resolve pretty urls.

Now, this is purely curiousity... is it possible to make it so that if any child of the http_response class is instantiated, all others are unable to be instantiated. So it would be a singleton, but a much bigger one... I guess. Does that make sense?

Posted: Thu Aug 17, 2006 10:38 am
by feyd
Possible, yes.

Posted: Thu Aug 17, 2006 10:45 am
by Luke
practical? useless?

Another question... with a singleton... I always have a hard time setting constructer arguments, because I don't like having to repeat the arguments from getInstance to __construct. Is there any way around this?

Posted: Thu Aug 17, 2006 10:51 am
by feyd
The Ninja Space Goat wrote:practical? useless?
I can see it both ways.
The Ninja Space Goat wrote:Another question... with a singleton... I always have a hard time setting constructer arguments, because I don't like having to repeat the arguments from getInstance to __construct. Is there any way around this?
Read here for some ideas:
viewtopic.php?t=53444
viewtopic.php?t=53274

Posted: Thu Aug 17, 2006 10:53 am
by Oren
Damn, feyd was faster :P

Posted: Thu Aug 17, 2006 11:17 am
by Jenk
registry, use an instanceof check in the registry when calling a new instance. Add an error of "DENIED!!1" for comedic hollywood esque comedy, and tada!

you could even make the singleton in the parent class and specify the child you wish to create and do all the above there.

Code: Select all

class ParentController
{
    private static instance;
    private static children = array('ParentController', /* allowed kids go here */);

    public static getInstance ($child = 'ParentController')
    {
        if (in_array($child, self::$children)) {

            if (!isset(self::$instance)) self::$instance = new $child;

            return self::$instance;
        } else {
            /* invalid child specified */
        }
    }

    /* etc.. */

}