Created
June 1, 2009 16:53
-
-
Save commana/121596 to your computer and use it in GitHub Desktop.
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 | |
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