Back
Implementing Abstract Factory
Singleton
Implementing Singleton
Forward


The Singleton Pattern

The singleton pattern isn't a natural to PHP. Its purpose is to ensure that there is only ever one instance of a class, and to provide a way of accessing that class. Given that PHP applications typically only execute for the length of a page load, you can usually keep track of your objects. But there are still times when it's extremely important to ensure that you always get the same copy of an object, and never make a new one.

You could, of course, assign your object to a global variable and always check to see if it exists, instantiating it if it doesn't. But that's not as elegant or foolproof a solution as a singleton - which is the whole point of design patterns.

Here's what using a singleton looks like:

<?php

require_once 'ClassName.php';

$instance = &ClassName::singleton();

The "&" is extremely important; it is what makes sure that you get back a reference to the object, instead of a copy. = &$foo is how to assign a reference in PHP.