Last active
December 16, 2015 08:28
-
-
Save PHLAK/5405555 to your computer and use it in GitHub Desktop.
Example PHP singleton class for reference. For the record, singletons are evil: http://stackoverflow.com/a/138012/27025
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 | |
/** | |
* Example PHP singleton class for reference. | |
* For the record, singletons are evil: | |
* http://stackoverflow.com/a/138012/27025 | |
*/ | |
class Singleton { | |
/** | |
* Private contructor to prevent direct access | |
*/ | |
private function __construct() { | |
// NULL | |
} | |
/** | |
* Return an instance of the class | |
* @return object Instance of Singelton() | |
*/ | |
public static function Initialize() { | |
// Setting some defaults | |
static $instance = null; | |
// Create new object if none exist | |
if ($instance === null) { | |
$instance = new Singleton(); | |
} | |
// Return object | |
return $instance; | |
} | |
} | |
$foo = Singleton::Initialize(); // Returns Singleton object | |
$bar = new Singleton(); // Trows error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment