title: When to use singletons in OOP?
body: <p>When reading about singletons, I have found this explanation as a reason to use singleton:</p>
  
  <blockquote>
    <p>since these object methods are not changing the internal class state, we
    can create this class as a singleton.</p>
  </blockquote>
  
  <p>What does this really mean ? When you consider that some method is not changing internal class state ? If it is a getter ? Can someone provide code examples for class that uses methods that are not changing its internal state, and therefore can be used as a singleton, and class that should not be a singleton ?</p>
  
  <p>Usually, when people are explaining singleton pattern, they use DB connection class as an example. And that makes sense to me, because I know that I want to have only one db connection during one application instance. But what if I want to provide an option to force using the new connection when I instantiate DB connection class? If I have some setter method, or constructor parameter that forces my class to open new connection, is that class still a subject to be a singleton ?</p>
  
  <p>I am using PHP, but may understand examples written in JAVA, C#...</p>
  
  <p>This is the <a href="http://www.yiiframework.com/doc-2.0/guide-concept-di-container.html#advanced-practical-usage" rel="nofollow noreferrer">article reference</a>. You can ctrl+f search for "internal". Basically, autor is explaining why FileStorage class is a good candidate to be a singleton. I do not understand this sentance </p>
  
  <blockquote>
    <p>"These operations do not change the internal class state, so we can
    create its instance once and use it multiple times."</p>
  </blockquote>
  
  <p>and therefore I do not understand when to use singletons.</p>
  
  <p>In their example, they have some FileStorage class :</p>
  
  <pre><code>class FileStorage
  {
      public function __contruct($root) {
          // whatever
      }
  
      public function read() {
          // whatever
      }
  
      public function write($content) {
          // whatever
      }
  }
  </code></pre>
  
  <p>And they say that this class can be a singleton since its methods read() and write() do not chage internal class structure. What does that mean ? They are not setters and class is automatically singleton ?</p>