Skip to content

Instantly share code, notes, and snippets.

@bueltge
Created January 13, 2012 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bueltge/1605673 to your computer and use it in GitHub Desktop.
Save bueltge/1605673 to your computer and use it in GitHub Desktop.
Vererbung Singleton; Gewährleistung, dass Kind-Klassen Singletons sind, spätere Kind-Klassen aber nicht irgendetwas anderes werden können
abstract class aloneSingleton {
private static $_instance;
final public static function getInstance() {
if ( ! is_null( self::$_instance ) ) {
if ( get_class(self::$_instance) !== get_called_class() )
throw new LogicException(get_called_class() . ' is an subclass of ' . __CLASS__
. ', instances are restricted to one instance overall, '
. 'you tried to access the wrong stage of inheritance, use '
. get_class(self::$_instance) . ' instead.');
else return self::$_instance;
} else {
self::$_instance = new static;
}
return self::$_instance;
}
abstract protected function __construct();
}
class A extends aloneSingleton {
protected function __construct() { echo __CLASS__.' created.'; }
}
class B extends aloneSingleton {
protected function __construct() { echo __CLASS__ . ' created.'; }
}
class C extends A {
protected function __construct() { echo __CLASS__ . ' created.'; }
}
class D extends B {
protected function __construct() { echo __CLASS__ . ' created.'; }
}
class Singleton {
private static $_instances = array();
final public static function getInstance() {
return ! isset( self::$_instances[ get_called_class() ] )
? self::$_instances[ get_called_class() ] = new static
: self::$_instances[ get_called_class() ];
}
final protected function __clone() {
}
protected function __construct () {
echo __CLASS__ . '-Class representation of construct.' . "\n";
}
}
class superSingleton extends Singleton {
protected function __construct () {
echo __CLASS__ . '-Class representation of construct.' . "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment