Helping ordinary people create extraordinary websites!
GET OUR NEWSLETTER
Your Email:
 

The Singleton Design Pattern for PHP

By Tony Marston
2005-07-29


A separate Helper method within each class

This method requires the addition of a getInstance() (or similar) method within each each and every class, similar to the following:

    function getInstance ()

// this implements the 'singleton' design pattern.
{
static $instance;

if (!isset($instance)) {
$c = __CLASS__;
$instance = new $c;
} // if

return $instance;

} // getInstance

It is referenced with code similar to the following:

    require_once 'std.datevalidation.class.inc';

$dateobj = DateClass::getInstance();

This method has the following advantages:

  • It provides a consistent method across all classes.

This method has the following disadvantages:

  • It requires that the class definition be pre-loaded.
  • It must be defined within each and every (sub)class where it will be needed. Due to the way that it works it cannot be inherited from a superclass because a static method in a superclass does not know of the existence of any subclasses therefore cannot be used to instantiate a subclass.


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:
» 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
» Desktop Application Development with PHP-GTK

Advertise with Us!


Tutorials Scripts Web Hosting Developer Manuals
Resources