Jump to content

php singleton


chaiwei

Recommended Posts

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

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.