title: Replace object with mock at the reference location in PHP
body: <p>In PHP project I have main singleton and some other singletons that uses the main one:</p>
  
  <pre><code>&lt;?php
  
  class SingletonMain
  {
      // Main singleton
      // ...
  }
  
  class SingletonA
  {
      protected $main;
  
      function __construct()
      {
          $main = SingletonMain::getInstance();
      }
  }
  
  class SingletonB
  {
      protected $main;
  
      function __construct()
      {
          $main = SingletonMain::getInstance();
      }
  }
  ?&gt;
  </code></pre>
  
  <p>I thought, maybe the easiest way to mock <strong>SingletonMain</strong> in <strong>SingletonA</strong> and <strong>SingletonB</strong> is by getting a reference to <strong>SingletonMain</strong> instance and performing this:</p>
  
  <ol>
  <li>Copy <strong>SingletonMain</strong> instance to <code>$temp</code>.</li>
  <li>Put <strong>MockSingletonMain</strong> instance in place of <strong>SingletonMain</strong>. By 'in place' I mean really, in the same reference location so that <strong>SingletonA</strong> and <strong>SingletonB</strong> could use a new mock immediately as if it was the original <strong>SingletonMain</strong>.</li>
  <li>Test.</li>
  <li>Revert <strong>SingletonMain</strong> instance from <code>$temp</code> in place.</li>
  </ol>
  
  <p>Is that possible to do? If not, what is the easiest way to mock <strong>SingletonMain</strong> in all <strong>SingletonsABCD</strong>....</p>
  
  <p>Currently, my only solution in mind is to explicitly set new mock in each of these leaf singletons and revert it once again in the end using normal assignment operator (<code>$this-&gt;main = $my_mock</code> and after testing <code>$this-&gt;main = SingletonMain::getInstance()</code>).</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>By reading several answers, I realized, I need to provide some more info. I have around 20-30 of these leaf singletons. The application was not designed to be tested in the first place several years ago, so now I am looking for the best way to go around the singleton pattern without breaking anything and changing as little as possible.</p>