Click here to Skip to main content
Click here to Skip to main content

Tagged as

Singleton Classes in PHP

, 28 Mar 2014
Rate this:
Please Sign up or sign in to vote.
This tutorial describes how to create and use singleton classes in PHP

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 may be useful when only one object of a 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 as follows:
  • 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 created. 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 singleton class? If your class inherits from some base class, you may implement it in the following way.

Let's say, you have a class named News (the base class) and its successors are LocalNews and MusicNews. You want each inheritor class to 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 == null) self::$_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
{
    public 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, the init() method of the parent class will be called, that will do all the 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 your application as expected - it will be printed one time only).

Sample 7. Debug the LocalNews Class

<?php
class LocalNews extends News
{
    private 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 for development teams. .

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

apphp
Founder ApPHP
United States United States
ApPHP.com founder, PHP Expert
http://www.apphp.com
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralEasy and Nice PinmemberSOHAM GANDHI29-Mar-14 3:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140814.1 | Last Updated 28 Mar 2014
Article Copyright 2014 by apphp
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid