Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You should just not use Singletons. They're Bad Practice(tm), as they introduce global state, which makes your Code much harder to test.</p> <p>One could rewrite your example by using Inversion Of Control this way:</p> <pre><code>&lt;?php // A simple Singleton for the Application function Application() { static $instance = null; if (null === $instance) { $instance = new Application; } return $instance; } class Application { protected $someService; function __construct() { $this-&gt;someService = new SomeService($this); } function test() { echo "Good."; } } class SomeService { protected $application; function __construct(Application $app) { $this-&gt;application = $app; } function test() { $this-&gt;application-&gt;test(); } } </code></pre> <p><code>Application</code> is your Main Application's class and <code>SomeService</code> is your <code>Singleton2</code>.</p> <p>No need for private constructors, etc. here and <code>SomeService</code> gets only instantiated once, with your App (considered you only instantiate your App once).</p> <p>Repeat this with other Services you want to add to your App instance.</p> <p>Some good articles on this, which are worth reading:</p> <ol> <li><a href="http://www.potstuck.com/2009/01/08/php-dependency-injection/" rel="nofollow">http://www.potstuck.com/2009/01/08/php-dependency-injection/</a></li> <li><a href="http://fabien.potencier.org/article/11/what-is-dependency-injection" rel="nofollow">http://fabien.potencier.org/article/11/what-is-dependency-injection</a></li> </ol>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload