chaiwei Posted July 22, 2009 Share Posted July 22, 2009 Hi, I am confused with "singleton". Is this a design pattern? let say: I got a class <?php class abc{ function __construct(){ } } //normally I do like this $obj = new abc(); with singleton: class abc{ protected static $obj=false; function __construct(){ } function static getInstance(){ if(self::$obj){ return self::$obj; }else { self::$obj = new abc(); return self::$obj; } } } //Is this singleton? Am I using the correct way? $obj = abc::getInstance(); ?> this have the advantage that I don't have to create so many object. so can I use this pattern for every class? Besides singleton, got another similar design pattern? Many people argue that singleton is a global variable and it is not a good pratice. What's wrong with global variable? Quote Link to comment Share on other sites More sharing options...
trq Posted July 22, 2009 Share Posted July 22, 2009 so can I use this pattern for every class? No. Only for objects that need a to guarantee there is only one instance available. so can I use this pattern for every class? A singleton is a singleton, there really isn't any similar pattern. What's wrong with global variable? They are unreliable. Quote Link to comment Share on other sites More sharing options...
chaiwei Posted July 23, 2009 Author Share Posted July 23, 2009 Hi, So singleton is also a global variable? why it is not reliable? Because of it can be modify in every script? Another better solutions not to use singleton? Thanks. Quote Link to comment Share on other sites More sharing options...
trq Posted July 23, 2009 Share Posted July 23, 2009 Singletons have nothing to do with global variables. I assume what you have read about is people creating an object registry (implemented as a singleton), these can be considered to have the same side effects as global variables. Global variable are unreliable because they can be overridden during your applications process. This way, they may not always contain what you think. Singletons have there place, but you definitional should use them minimally. Quote Link to comment Share on other sites More sharing options...
chaiwei Posted July 23, 2009 Author Share Posted July 23, 2009 yes, I have read it. So Singleton can use, but object registry should not use right? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.