Singleton Classes in PHP
In this PhpRiot Snippet I will show you how to create and use singleton classes. A singleton class is a class that can instantiated once only. While it may not come up frequently, it can be a useful technique when it simply doesn't make sense to have than one instance of a class.
To achieve this we cannot instantiate it directly using the new keyword. Instead, we must use a static class method to access the create and access the instance.
The key steps in creating singleton classes are as follows:
- Prevent direct instantiation by making the contructor private
- Store the only instance of the class as a static property of the class.
- Provide a static method to access the instance. The instance is created the first time this method is called.
Let's say we want to create a singleton class called MySingleton. The following code defines this class, including the private constructor so it cannot be directly instantiated.
class MySingleton { private function __construct() { // put normal constructor code. // it will only ever be called once } public function someMethod() { echo "Doing something!"; } }
Next we add a static property called $_instance. We make this private so it cannot be accessed except through the static method we'll also create. The convention for the singleton accessor method is to name is GetInstance (or getInstance, depending on your preference).
class MySingleton { private static $_instance; public static function GetInstance() { if (!self::$_instance instanceof self) { self::$_instance = new self(); } return self::$_instance; } private function __construct() { // put normal constructor code. // it will only ever be called once } public function someMethod() { echo "Doing something!"; } }
The GetInstance 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 can be returned.
The following listing shows how you can access and use the object.
require_once('MySingleton.php'); $obj = MySingleton::GetInstance(); $obj->someMethod();
Other Options
- Download a PDF version of this article
- Put your PHP knowledge to the test with our online and iPad/iPhone quizzes
- View or post comments for this article
- Browse similar articles by tag: OOP, PHP




