Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

The Singleton Design Pattern for PHP

By Tony Marston
2005-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 new command 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


 | Bookmark
Related Tutorials:
» Zend Framework Tutorial
» Port Scanning and Service Status Checking in PHP
» Web Database Access from Desktop Applications
» CubeCart 3.0 Installation and Configuration
» PHP Site Search Made Easy
» Installing and Configuring Drupal 6.1