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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.