Skip to content

Instantly share code, notes, and snippets.

@commana
Created June 1, 2009 16:53
Show Gist options
  • Save commana/121596 to your computer and use it in GitHub Desktop.
Save commana/121596 to your computer and use it in GitHub Desktop.
<?php
class UberSingleton {
private $state = 0;
private static $instance;
private function __construct() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self;
}
return self::$instance;
}
public function __clone() {
throw new Exception("Singleton!");
}
public function __sleep() {
throw new Exception("Singleton²!");
}
public function doSomething() {
$this->state++;
}
public function __toString() {
return "Singleton: " . $this->state . "<br />";
}
}
//$obj = new UberSingleton(); // Fatal error: Call to private UberSingleton::__construct() from invalid context
$obj = UberSingleton::getInstance();
//$otherObj = clone $obj; // Fatal error: Uncaught exception 'Exception' with message 'Singleton!'
//$serialized = serialize($obj); // Fatal error: Uncaught exception 'Exception' with message 'Singleton²!'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment