Singleton Pattern in PHP

Feb 6, 2012 by

Singleton Pattern in PHP

The Singleton Pattern is one of the best and well-known design patterns.A singleton Pattern in one kind of design pattern and it comes when you want single instance for whole application(means you want application wide instance).

Specifically, for a login object, you would want each and every place in the application
that wants to print something to the log that user have access to it and so to centralize the logging mechanism and to handle the filtering of messages according to log level settings we can use Singleton patterns.

To Make a class as a singleton class in usually done with implementing a static class method.static method returns the only single instance of the class.When first time you call this method, it creates an instance, saves it in a private static variable and returns the instance. The next time, it just returns you a handle to the already created instance.

Example:

Let’s have a look with Singleton Pattern

PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class User {
    static function getInstance()
    {
    if (self::$instance == NULL) { // If instance is not created yet, will create it.
        self::$instance = new User();
    }
    return self::$instance;
    }
    private function __construct()
    // Constructor method as private so by mistake developer not crate
    // second object of the User class with the use of new operator
    {
    }
    private function __clone()
    // Clone method as private so by mistake developer not crate
    //second object of the User class with the use of clone.
    {
    }
    
    function Log($str)
    {
   echo $str;
    }
    static private $instance = NULL;
}
User::getInstance()->Log("Welcome User");

Pattern User::getInstance() gives you access to the logging object from anywhere in your application, whether it is from a function, a method, or the global scope.

In above example, the constructor and clone methods are defined as private.
This is done so that a developer can’t create a second instance of the User class using the new or clone operators; therefore, getInstance() is the only way to access the singleton class instance.

Related Posts

Tags

Share This

1 Comment

  1. Nice article. Just an FYI, using PHP5.4 traits, singletons become much easier to scale across any number of classes you need.

Trackbacks/Pingbacks

  1. Singleton Pattern in PHP | PHP | Syngu - [...] The Singleton Pattern is one of the best and well-known design patterns.A singleton Pattern in one kind of design ...

Leave a Comment

Top of Page