原文出处http://en.wikipedia.org/wiki/Singleton_pattern
<?php
class Singleton {
// object instance
private static $instance;
// The private construct prevents instantiating the class externally. The construct can be
// empty, or it can contain additional instructions...
private function __construct() {
...
}
// The clone method prevents external instantiation of copies of the Singleton class,
// thus eliminating the possibility of duplicate classes. The clone can be empty, or
// it can contain additional code, most probably generating error messages in response
// to attempts to call.
private function __clone() {
...
}
//This method must be static, and must return an instance of the object if the object
//does not already exist.
public static function getInstance() {
if (!self::$instance instanceof self) {
self::$instance = new self;
}
return self::$instance;
}
//One or more public methods that grant access to the Singleton object, and its private
//methods and properties via accessor methods.
public function doAction() {
...
}
}
//usage
Singleton::getInstance()->doAction();
?>