Here's a little class I wrote which I found useful. It'll store a collection of singletons, and create them where necessary. Just include the classes you want to use as singletons at the top, and request them as per the usage.
I'm not sure if this is a good or bad thing, I'm still learning PHP5 OO techniques 🙂
<?php
require_once("myclass.php");
/**
* Repository of static instances
* Checks repository for 'live' instances
* Creates a new instance if required
*/
class Repository {
static private $repository = array();
private function __construct(){}
/**
* Returns a static instance of $class
* Creates a new instance...in the first...instance
* @param string $class
* @return obj $$class
*/
static function getInstance($class){
if(!isset(Repository::$repository[$class])){
Repository::$repository[$class] = new $class;
}
return Repository::$repository[$class];
}
}
// Usage:
$staticinstance = Repository::getInstance("MyClassName");
?>