user160820
user160820

Reputation: 15230

Singleton Object in PHP

I am learning PHP and trying to understand Singleton Object but can't really understand what does it actually means?

If I create a Singleton Object, is it one object for all the clients or every client (browser session) will have its own Singleton Object?

Upvotes: 2

Views: 473

Answers (5)

Abhishek
Abhishek

Reputation: 5738

Singleton is design pattern and basically means:

  • Make sure there can be only one instance of a class at any time.
  • Provide global access to that single instance from anywhere within
    your application.

Example of singleton in PHP:

class Singleton
{
    protected static $instance = null;
    protected function __construct()
    {

     }

    public static function getInstance()
    {
        if (!isset(static::$instance)) {
            static::$instance = new static;
        }
        return static::$instance;
    }
}

Surprise you don't need Singleton In PHP ,Here's why?

Link of gordon blog why its of no use in PHP: http://blog.gordon-oheim.biz/2011-01-17-Why-Singletons-have-no-use-in-PHP/

Upvotes: 4

s3v3n
s3v3n

Reputation: 8466

If you come from the Java land than you might have the impression that a singleton is a single instance on the whole webserver.

In PHP, whenever a new request comes to the server, PHP runs all the code and creates new objects and instances so unlike Java, in PHP, the singleton will be the only instance in the request context, not the server.

I hope this answers your question :)

Upvotes: -1

Eternal1
Eternal1

Reputation: 5625

PHP Sessions do not share data natively, so Singleton simply ensures, that you use one and only one object instance inside your Session, which is quite handy for Configuration, Database connection, cache objects for example.

There are several ways to achieve that. First one, is using static method. While it is very simple it promotes tight coupling and is very hard to unit test, which becomes a major concern when your project grows larger. Second one is simply saving an object inside some container property, and passing that container along through all the methods that depend on your singleton instance. It is harder at first, and there are many ways to achieve that, most common being the multitude of Dependency Injection methods.

Upvotes: 0

Pakspul
Pakspul

Reputation: 648

A singleton object is a single instance of a particular class. In each PHP request this instance will be made, it's not even per session but really per request a person makes on your system.

For more knowledge check out the wikipedia page, also on how to create the pattern: http://en.wikipedia.org/wiki/Singleton_pattern

Upvotes: 0

ElTête
ElTête

Reputation: 585

I think that each client can have an instance of the object, but just one.

check this

Upvotes: 0

Related Questions