Singletons and inheritance

Not for 'how-to' coding questions but PHP theory instead, this forum is here for those of us who wish to learn about design aspects of programming with PHP.

Moderator: General Moderators

Post Reply
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Singletons and inheritance

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Possible, yes.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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
User avatar
Oren
DevNet Resident
Posts: 1640
Joined: Fri Apr 07, 2006 5:13 am
Location: Israel

Post by Oren »

Damn, feyd was faster :P
User avatar
Jenk
DevNet Master
Posts: 3587
Joined: Mon Sep 19, 2005 6:24 am
Location: London

Post 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.. */

}
Post Reply