Static init?

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
Gambler
Forum Contributor
Posts: 246
Joined: Thu Dec 08, 2005 7:10 pm

Static init?

Post by Gambler »

Is there any way to assign object to static variable wihout doing something like this?

Code: Select all

<?php
Session::init();

class Session{
    static $var;
    
    static function init(){
        self::$var = new TestClass();
    }
}
?>
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Post by Christopher »

It is not clear from your question what you are asking? You are assigning an object to a static. Usually you would do a check to see if the static is already set so you did not keep recreating the property -- thereby creating a Singleton.
(#10850)
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

Yeah it looks like you're trying to create a sort of singleton.... one that seemingly doesn't hold an instance of itself. Hmm...

What are you trying to acheive? I'm almost inclined from the nature of your question to have a stab in the dark and think you may be looking at creating a static registry.
Gambler
Forum Contributor
Posts: 246
Joined: Thu Dec 08, 2005 7:10 pm

Post by Gambler »

Sorry for the vague question. I think singleton is indeed the only "clean" way to do this, although I don't like singletons.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

So use a registry and factory or servicelocator pattern instead.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

feyd wrote:So use a registry and factory or servicelocator pattern instead.
I agree. Singletons can be ugly and end up creating essentially the same problems as globals do. There's no reason to "dislike" them but it doesn't appear that what you want to do is a bog-standard singleton. Have you looked at the registry pattern? You can create a really convenient extended registry in PHP5 too.
Post Reply