function & getSingleton() { $class=__CLASS__; // getting current class name // need to build singleton ? if (!isset($GLOBALS['singletons'][$class])) { // getting arguments to forward $args=func_get_args(); /* building instanciation code, forwarding arguments creating singleton and a single global reference per class name */ $eval='$GLOBALS[\'singletons\'][$class]=& new $class('; // adding arguments to constructor for ($f=0; $f<count($args); $f++) $eval.='$args['.$f.'],'; // deleting last unnecessary ',' and closing call $eval=substr($eval,0,-1).');'; // executing instanciation code eval($eval); } // throwing instance return $GLOBALS['singletons'][$class]; }

So you can get a single instance of your class with a static call of getSingleton, like your_class::getsingleton($arg1, $arg2,...);. You can edventually add an alert in the class constructor like this :

function the_class_constructor_method() { if (isset($GLOBALS['singletons'][__CLASS__])) { trigger_error("Use ".__CLASS__."::getSingleton(); to get a single instance of ".__CLASS__); } }

Please note that this isn't the clean, righteous way to implement Singleton pattern : because in php4 it seems not possible to have the class constructor returning anything else than a new instance of the class, nor to make the constructor private. Therefore it is still possible to have multiple instances of the class, by calling its constructor directly.