PHP Singletons


It has been quite some time since my last post. However, I will be posting a few object oriented PHP tips over the next few days, especially in regard to design patterns. My first post on the subject will deal with Singletons. As a side note, don't overuse any of these design patterns. They have their purpose and even though you may be tempted to use them in everything after you learn them, notice their benefits and work with them where they can benefit your overall system design.

Singletons are useful when you want only one instance of a class. Thus their name. You may scratch your head and wonder why you'd want to use this design pattern. There are some advantages to it. Firstly, you will reduce resource requirements for your application. It guarantees that you will only have one object taking up memory. Secondly, a singleton can be useful for simulating global variables. You can set a property of the object and access it anywhere in your application.

In a PHP application this can come in handy when you are using controllers in your own MVC framework, when you have a helper class that you only need a single instance of ever, and in any other case where only one object of a class is needed/wanted.

Here is an example of a PHP Singleton:

1
2
3
4
5
6
7
8
9
10
11
12
<?php
  class Singleton {
    private static $_instance;
    private function __construct() {}
    public static function getInstance() {
      if(!self::$_instance) {
        self::$_instance = new self();
      }
      return self::$_instance;
    }
  }
?>

We have a private static property called $_instance. This will hold our single instance of the class. The constructor for the class is private so it can never be called from outside of the class. Thus, it can not be called directly. We call the constructor inside the public static method getInstance(). The whole purpose of this static method is to check to see if there is an instance of the class and if not, create it. It then returns that single instance. So the $_instance property of the class holds the single instance of itself. The recursion can be confusing.

In order to use the singleton, you simply call the static getInstance() method and assign the reference to a variable, or if you only need to execute a single method, you can call the method in a chain. Here is an example each:

1
$mySingleton = Singleton::getInstance();
1
Singleton::getInstance()->someMethod();
  1. No comments yet.
(will not be published)