Re: Traits and static methods
| From: | Sebastian Bergmann | Date: | Mon, 22 Nov 2010 11:52:10 +0000 |
| Subject: | Re: Traits and static methods | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-50409@lists.php.net to get a copy of this message | ||
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/