Page 1 of 1

Static init?

Posted: Wed Jun 14, 2006 2:22 pm
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();
    }
}
?>

Posted: Wed Jun 14, 2006 4:41 pm
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.

Posted: Wed Jun 14, 2006 6:43 pm
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.

Posted: Thu Jun 15, 2006 3:04 pm
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.

Posted: Thu Jun 15, 2006 3:06 pm
by feyd
So use a registry and factory or servicelocator pattern instead.

Posted: Thu Jun 15, 2006 4:08 pm
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.