The Singleton Design Pattern for PHP
By Tony Marston2005-07-29
A non-class Helper function
This method uses a separate non-class function as a "helper". It contains code similar to the following:
function getDateObject ()
// return the handle to the standard date validation object.
{
static $instance;
if (!is_object($instance)) {
// does not currently exist, so create it
require_once 'std.datevalidation.class.inc';
$instance = new DateClass;
} // if
return $instance;
} // getDateObject
It is referenced with code similar to the following:
$dateobj = getDateObject();
This method has the following advantages:
- Because it is designed to work with a single specific class it can also take the responsibility of ensuring that the relevant class file is loaded when necessary.
This method has the following disadvantages:
- It requires a separate helper function for each different class.
Tutorial Pages:
» Introduction
» A non-class Helper function
» A separate Helper method within each class
» A single Helper method for all classes
» References
» Conclusion
