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.

Read moreCreating a singleton class in PHP