Skip to content

Instantly share code, notes, and snippets.

@mnapoli
Last active December 15, 2015 07:09
Show Gist options
  • Save mnapoli/5221664 to your computer and use it in GitHub Desktop.
Save mnapoli/5221664 to your computer and use it in GitHub Desktop.
"Optional singleton" pattern
<?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