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? Link to comment https://forums.phpfreaks.com/topic/166908-php-singleton/ 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. Link to comment https://forums.phpfreaks.com/topic/166908-php-singleton/#findComment-880050 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. Link to comment https://forums.phpfreaks.com/topic/166908-php-singleton/#findComment-880934 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. Link to comment https://forums.phpfreaks.com/topic/166908-php-singleton/#findComment-880947 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? Link to comment https://forums.phpfreaks.com/topic/166908-php-singleton/#findComment-880960 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.