Am 16.11.2010 18:46, schrieb Simas Toleikis:
> p.s. a Singleton-Trait implementation could look like:
>
> trait Singleton {
> public static function getInstance() { ... }
> }
>
> class Child extends Parent {
> use Singleton;
> }
>
> Child::getInstance();
This is not really a good example as the getInstance() method alone is
not sufficient for a reusable implementation of the Singleton pattern.
A trait for a reusable implementation of the Singleton pattern should
look more like
trait Singleton
{
private static $uniqueInstance = NULL;
protected function __construct() {}
private final function __clone() {}
public static function getInstance()
{
if (self::$uniqueInstance === NULL) {
self::$uniqueInstance = new Singleton;
}
return self::$uniqueInstance;
}
}
which of course does not work as traits are stateless and
class MySingleton
{
use Singleton;
}
MySingleton::getInstance();
results in
Access to undeclared static property: MySingleton::$uniqueInstance
And rightfully so. Nobody should need a mechanism to make it as easy as
pie to clutter the code base with singletons ;-)
--
Sebastian Bergmann Co-Founder and Principal Consultant
http://sebastian-bergmann.de/ http://thePHP.cc/
--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: http://www.php.net/unsub.php