Skip to content

Instantly share code, notes, and snippets.

@PHLAK
Last active December 16, 2015 08:28
Show Gist options
  • Save PHLAK/5405555 to your computer and use it in GitHub Desktop.
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
<?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