phpbar.de logo

Mailinglisten-Archive

[php] Singleton

[php] Singleton

Maik Ryssel maik at laubegaster.de
Fre Feb 10 13:11:45 CET 2006


Sebastian Mendel schrieb:

>mit php 5 klappt es so
>
>php 4:
>
>class Singleton
>{
>     var $_instances = array();
>
>     function &instance($class) {
>	   
>         if (!isset($this->_instances[$class]) || 
>!is_object($this->_instances[$class])) {
>             $this->_instances[$class] = new $class();
>         }
>
>         $pointer =& $this->_instances[$class];
>
>         return $pointer;
>     }
>}
>
>function &singleton($class) {
>
>     static $singleton;
>
>     if (!is_object($singleton)) {
>         $singleton = new Singleton();
>     }
>
>     $instance =& $singleton->instance($class);
>
>     return $instance;
>}
>
>class Foo
>{
>     var $count = 0;
>
>     function getCount() {
>         $this->count++;
>         return $this->count;
>     }
>}
>
>$obj =& singleton('Foo');
>echo "Erster Aufruf erwartet 1, Ergebniss = ".$obj->getCount()."<br>";
>$obj2 =& singleton('Foo');
>echo "Zweiter Aufruf erwartet 2, Ergebniss = ".$obj2->getCount()."<br>";
>  
>
Danke Super funzt....

php::bar PHP Wiki   -   Listenarchive