The Singleton Design Pattern for PHP
By Tony Marston2005-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:
|
|
|||||||||
You might also want to check these out:
|
Leave a Comment on "The Singleton Design Pattern for PHP"
You must be logged in to post a comment.
Link to This Tutorial Page!

