Creating a singleton class in PHP

PHP began as a language which was not designed around object oriented principles, but lately you’d be hard pressed to find a PHP application that does not utilize classes, objects, and other object oriented design concepts.  Now that PHP is big into the OO world, you might be wondering how you can implement some common object oriented design patterns like a “singleton” in PHP.

In this article, I’ll go through how to create a singleton class and also briefly describe when you might want to use a singleton design pattern in your application.

OK, so first, what is a singleton? The singleton design pattern is where you never want to have more than a single (hence the name singleton) instance of a given class.  In normal use of classes and objects, you define a class once and then you create many instances (objects) in your application.  Each instance has its own properties.  For example, if you had a class “Person” with attributes “first_name” and “last_name”.  Each instance of “Person” might have different values for “first_name” and “last_name”.  In a singleton instance, there can never be more than one instance of a given class in the application, ever.  Why would you want this? Lets say you wanted your application to only every have one connection to a database.  In this case, you could create a singleton class called “DatabaseConnection” which would ensure that there would only ever be one database connection in your application.  It also means that you can access that one instance globally, so you don’t have to pass your database connection object between functions because it can be accessed from anywhere.  Here’s some example code which implements a “DatabaseConnection” singleton class.

<?php

class DatabaseConnection {
	private static $singleton_instance = null;
	
	private function construct__() {
		// Declaring the constructor as private ensures
		// that this object is not created as a new instance
		// outside of this class.  Therefore you must use
		// the global_instance function to create this
                // object.
	}
	
	public static function global_instance() {
		static $singleton_instance = null;
		if($singleton_instance === null) {
		  $singleton_instance = new DatabaseConnection();
		}
		
		return($singleton_instance);
	}

	public function exec_query($query) {
		print "Running query: " . $query;
		// This is just an example, but this is where you'd
		// normally run the database query
	}
	
}

// We create a database instance by running the static function
// which returns the singleton instance of the class
$db_connection = DatabaseConnection::global_instance();

// Call an function on the global instance of the object.
$db_connection->exec_query("INSERT INTO my_table (1)");

?>;

In this example, you can see that the magic happens in the “global_instance” function.  This function checks to see if an instance of the class has been created yet or not.  If it hasn’t it creates a new instance.  If it has been created before, it returns the singleton instance which was previously created.  The other important part is that you need to make the constructor function “private”.  This ensures that the class can not be instantiated outside the class, only the global_instance function can be used to create it.  That’s it!

One note I should make.  This design pattern is debated as it isn’t considered “clean” object oriented programming.  When writing OO programs it’s important to ensure that classes can be easily extended, and ideally that instances of a class don’t affect other instances.  For example in unit tests using a singleton class, if your first test failed, it could affect the second test (which in an ideal world is a no-no in unit tests).  So, if “clean” and segregated code is your objective, maybe consider a different method of accomplishing this.

1 thought on “Creating a singleton class in PHP”

  1. I started to write an article on modifiers here ( http://www.searchconsort.com/h/D0000D.php ) and how Java and PHP modifiers are the same and different. I was wondering if you could answer how PHP would handle synchronization in the case where multiple threads could be constructing an instance at once. In Java you might put an intrinsic lock around the block. Is there a way that this gets done in PHP?

    public class SingletonExample {
    private static SingletonExample instance = null;
    private static int value = 0;
    private SingletonExample() {
    ++this.value;
    }
    public static SingletonExample getInstance() {
    if(instance!=null)
    return instance;
    synchronized(SingletonExample.class) {
    instance = new SingletonExample();
    return instance;
    }
    }
    public void printValue() {
    System.out.print( this.value );
    }

    public static void main(String [] args) {
    SingletonExample instance = getInstance();
    instance.printValue();
    instance = getInstance();
    instance.printValue();
    }
    }

Leave a Comment