The Singleton Design Pattern for PHP
By Tony Marston2005-07-29
A single Helper method for all classes
This requires the creation of a separate class (called singleton in this example) with a single method (called getInstance() in this example).
class singleton
{
function getInstance ($class)
// implements the 'singleton' design pattern.
{
static $instances = array(); // array of instance names
if (!array_key_exists($class, $instances)) {
// instance does not exist, so create it
$instances[$class] =& new $class;
} // if
$instance =& $instances[$class];
return $instance;
} // getInstance
} // singleton
It is referenced with code similar to the following:
require_once 'std.datevalidation.class.inc';
$dateobj = singleton::getInstance('DateClass');
This method has the following advantages:
- It provides a single method which will work for any and all classes and subclasses.
- It does not require a method to be duplicated within each class or subclass.
This method has the following disadvantages:
- It requires that the class definition be pre-loaded. If the file name could be deduced or constructed from the class name then could be built into the
getInstance()method. - Although the class names used with the
newcommand are case-insensitive, when used as keys within an associative array they are not. This means that 'classname', 'ClassName' and 'CLASSNAME' would be treated as different keys in the array, therefore would return different instances.
Tutorial Pages:
» Introduction
» A non-class Helper function
» A separate Helper method within each class
» A single Helper method for all classes
» References
» Conclusion
