Abstract Singleton

Aus php bar

Wechseln zu: Navigation, Suche

Ab PHP 5.3 möglich, da get_called_class() erst dort verfügbar:

 abstract class Singleton
 {
     private static $instances = array();
 
     final public static function getInstance()
     {
         $class = get_called_class();
         if (empty(self::$instances[$class])) {
             $rc = new ReflectionClass($class);
10             self::$instances[$class] = $rc->newInstanceArgs(func_get_args());
11         }
12         return self::$instances[$class];
13     }
14 
15     final public function __clone() {
16         throw new Exception('This singleton must not be cloned.');
17     }
18 }
19 
20 class ConcreteSingleton extends Singleton
21 {
22     public function __construct($string, array $array)
23     {
24         echo __METHOD__ . '(' . $string . ', ' . print_r($array, true) . ')';
25     }
26 }
27 
28 $test = ConcreteSingleton::getInstance('Hello World', array(1,2,3));
Persönliche Werkzeuge