Singleton Classes in PHP

This tutorial describes how to create and use singleton classes in PHP.
Provided by Leumas Naypoka / www.apphp.com

Introduction

In this tutorial we'll learn how to create and use singleton classes. A singleton class is a class that can be instantiated only once. This is may be useful when only one object of certain class is needed to coordinate across your system. While it may not come up frequently, it can be a useful technique when it simply doesn't make sense to have more than one instance of a class.

Implementation

To attain this target we cannot instantiate it directly using the new keyword. Instead, we must use a static method of the class to create and access the instance.

The key steps in creating singleton classes are following:
  • To prevent direct instantiation by making the constructor private (optional)
  • To store the only instance of the class as a static property of the class.
  • Have to provide a static method to access the instance. The instance is created the first time this method is called.

So let's create our first singleton class that called MySingleton. The code below defines this class, including the private constructor so it cannot be directly instantiated.

Sample 1. Defining the MySingleton class
<?php
class MySingleton
{
    private function 
__construct(){
        
// constructor code here it will be called once only
    
}

    public function 
someMethod(){
        echo 
"Doing something!";
    }
}
?>

The next step we do is to add a static property called $_instance. We need to declare it private so it cannot be accessed except through the static method we'll also create. The convention for the singleton accessor method's name is getInstance (or init, depending on your preferences).

Sample 2. Turning MySingleton into a real singleton class
<?php
class MySingleton
{
    private static 
$_instance;
    
    private function 
__construct(){
        
// constructor code here it will be called once only
    
}

    public static function 
init(){
        if(
self::$_instance == null){
            
self::$_instance = new self();
        }
        return 
self::$_instance;            
    }
        
    public function 
someMethod(){
        echo 
"Doing something!";
    }
}
?>

The init() method first checks if the $_instance property is a MySingleton. If it's not, the one and only instance is creating. Once it has been created it may be returned.

The following code shows you how to create and use the object of singleton class.

Sample 3. Usage of the MySingleton class
<?php
require_once('MySingleton.php');

$obj MySingleton::init();
$obj->someMethod();
?>

You may see, that creating and working with singleton class is not so hard, but what about automatic creating of singlon class? If your class inherits from some base class you may implement it in a following way.

Lets say, you have a class named News (the base class) and it's successors LocalNews and MusicNews. You want each inheritor class will have init() method that will be inherited from the base class.

First, we need to create a base (parent) class:

Sample 4. Creating a base (parent) class
<?php
class News
{
    private static 
$_instance;

    
/* returns instance of the class */
    
public static function init()
    {
        
$className get_called_class(); /* PHP >= 5.3 */
        
if(self::$_instance == nullself::$_instance = new $className();
        return 
self::$_instance;
    }
}
?>

Now, let's create a child class. We don't redefine init() method, it will be inherited from the base class:

Sample 5. Creating a child class
<?php
class LocalNews extends News
{
    private function 
__construct(){
        
// constructor code here it will be called once only
    
}
}
?>

The code below shows you how to create and use this object of singleton class.

Sample 6. Usage of the LocalNews class
<?php
$obj 
LocalNews::init();
$obj->someMethod();
?>

In this case will be called init() method of the parent class, that will do all needed work for us. That's all, now you know how to create and use singleton pattern for classes in PHP. If you need to debug your application, you may add some log code in constructor of your child class to check how many times it will be called (if you created you application as expected - it will be printed one time only).

Sample 7. Debug the LocalNews class
<?php
class LocalNews extends News
{
    public function 
__construct(){
        echo 
"I'm called! <br />";
    }
}

$obj1 LocalNews::init();
$obj2 LocalNews::init();
$obj3 LocalNews::init();
?>

Conclusion

There are various different ways of implementing the Singleton design pattern in PHP. This pattern is a very useful mechanism for providing a single point of object access in an object-oriented application. Regardless of the implementation used, this pattern provides a commonly understood concept that can be easily shared among design and for your development teams.

You may also download all examples in one archive file:
DOWNLOAD ALL
example files ▼



Comments


Please post only comments related to the original tutorial. Be polite and helpful, do not spam or offend others.
Create Your Free Account
Please remember that this information is essential to use our services correctly.
After creating the account you will be able to download all of our FREE products.
Fields marked with * are mandatory






Please send me information about updates, new products, specials and discounts from ApPHP!
We recommend that your password should be at least 6 characters long and should be different from your username/email. Please use only letters of the English alphabet to enter your name.

Your e-mail address must be valid. We use e-mail for communication purposes (order notifications, etc). Therefore, it is essential to provide a valid e-mail address to be able to use our services correctly.

All your private data is confidential. We will never sell, exchange or market it in any way. Please refer to Privacy Policy.

By clicking "Create Account", you are indicating that you have read and agree to the ApPHP Terms & Conditions.