Last active
December 15, 2015 07:09
-
-
Save mnapoli/5221664 to your computer and use it in GitHub Desktop.
"Optional singleton" pattern
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// See also http://en.mnapoli.fr/the-optional-singleton-pattern/ | |
class MyService | |
{ | |
private static $singletonInstance = null; | |
/** | |
* Keep the constructor public | |
*/ | |
public function __construct() { | |
} | |
/** | |
* Returns an instance of the class (Singleton design pattern) | |
* @return MyService | |
*/ | |
public static function getInstance() { | |
if (self::$singletonInstance === null) { | |
self::$singletonInstance = new self(); | |
} | |
return self::$singletonInstance; | |
} | |
} | |
// Singleton usage | |
$myService = MyService::getInstance(); | |
// Classic usage | |
$myService = new MyService(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment