Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php: singleton VS full static class? When use what?

I understand that singleton enforces a class to be created once. But why should an instance exists if I dont access it directly? Why is that pattern for, isn't it easier just use full static class with static methods and datas?

like image 408
deeped Avatar asked Jul 26 '11 11:07

deeped


2 Answers

Some time ago I was asked what is the benefit of using singleton over of using static class, here is my response:

  • Static class leads to invisible dependencies - that is a class that use the static class, but that class is not part of the class' interface. Singleton also allows this, because it provides global access point, but it's instance can be passed as an argument to the class / method
  • If there is any initialization, as the connect method, it should be called from each class method, which leads to duplicated code. On the other hand, the initialization of the singleton is performed in the constructor, which is called just once from the getInstance() method
  • Singleton can be easily refactored in a factory, adding a parameter to the getInstance() method and returning different instances
  • Static class is harder to extend, because if we want to override a method, that is called within the class with self::methodName(), we should override the caller as well (although in PHP 5.3 there is a late static binding, which can be used to avoid those problems)
  • If you need to add an argument, needed for all of the methods, you can easily do this in singleton because of the single access point, but you can't in a static class
like image 174
Maxim Krizhanovsky Avatar answered Sep 22 '22 13:09

Maxim Krizhanovsky


The major difference between a static class and a singleton is that with the static class, you need to hardcode the class name in your code everywhere you use it:

StaticClass::doSomething();
StaticClass::doSomethingElse();

While with a singleton, you only need to hardcode the class name once:

$singleton = SingletonClass::getInstance();

// other code does not need to know where $singleton came from,
// or even that class SingletonClass exists at all:
$singleton->doSomething();
$singleton->doSomethingElse();

Another important difference is that singleton classes can be part of hierarchies and can implement interfaces.

This does not mean that Singleton (the pattern) is good and should be used liberally. But it is better than using a static class directly.

like image 40
Jon Avatar answered Sep 26 '22 13:09

Jon