fredbird.org

Les vastes plaines ouvertes, les belles collines et les eaux qui serpentent en méandres compliqués n'étaient pas "'sauvages" à nos yeux. Seul l'homme blanc trouvait la nature sauvage et pour lui seul la terre était "infestée" d'animaux "sauvages" et de peuplades "sauvages". A nous, la terre paraissait douce, et nous vivions comblés des bienfaits du Grand Mystère. Elle ne nous devint hostile qu'à l'arrivée de l'homme barbu de l'est qui nous accable, nous et les familles que nous aimons, d'injustices insensées et brutales. C'est quand les animaux de la forêt se mirent à fuir son approche que commença pour nous "l'Ouest Sauvage"

-- Luther Standing Bear, Sioux Oglala

fil atom des web logs

Generic php4 method to get a singleton

Quickly, a generic method to get a singleton in php4. Juste paste this method in your class definition :

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.

Fred Bird Quintidi 25 Floreal an 213
Commenter

Le monde est grand, le web le rétrécit. Un point de vue libertaire sur le vaste monde et nos petites vies.

Thèmes traités : politique, web & informatique, espace, Amérindiens, société, culture etc

Tous les contenus Accueil presence status jabber

Contenus similaires

Souscriptions

+ rojo + bloglines + Google reader + My Yahoo + del.icio.us add blogmarks add netvibes

Pub

Ouvaton, hébergeur coopératif Firefox Framasoft Ubuntu