ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 ### 概念示例 <details> <summary>main.php</summary> ``` <?php class Singleton { private static $instances = []; protected function __construct() { } protected function __clone() { } public function __wakeup() { throw new \Exception("Cannot unserialize a singleton."); } public static function getInstance(): Singleton { $cls = static::class; if (!isset(self::$instances[$cls])) { self::$instances[$cls] = new static(); } return self::$instances[$cls]; } public function someBusinessLogic() { // ... } } $s1 = Singleton::getInstance(); $s2 = Singleton::getInstance(); if ($s1 === $s2) { echo "相等"; } else { echo "不相等"; } ``` </details> <br /> 输出 ``` 相等 ``` ### 单例日志与配置 采用单例服用的方式 <details> <summary>main.php</summary> ``` <?php class Singleton { // 使用数组,可以被其他所有单利类所继承 private static $instances = []; protected function __construct() { } protected function __clone() { } public function __wakeup() { throw new \Exception("Cannot unserialize singleton"); } public static function getInstance() { $subclass = static::class; if (!isset(self::$instances[$subclass])) { self::$instances[$subclass] = new static(); } return self::$instances[$subclass]; } } class Logger extends Singleton { private $fileHandle; protected function __construct() { $this->fileHandle = fopen('php://stdout', 'w'); } public function writeLog(string $message): void { $date = date('Y-m-d'); fwrite($this->fileHandle, "$date: $message\n"); } public static function log(string $message): void { $logger = static::getInstance(); $logger->writeLog($message); } } class Config extends Singleton { // 属性只有一份 private $hashmap = []; public function getValue(string $key): string { return $this->hashmap[$key]; } public function setValue(string $key, string $value): void { $this->hashmap[$key] = $value; } } Logger::log("Started!"); $l1 = Logger::getInstance(); $l2 = Logger::getInstance(); if ($l1 === $l2) { Logger::log("Logger 相同"); } else { Logger::log("Loggers 不同"); } $config1 = Config::getInstance(); $login = "test_login"; $password = "test_password"; $config1->setValue("login", $login); $config1->setValue("password", $password); $config2 = Config::getInstance(); if ($login == $config2->getValue("login") && $password == $config2->getValue("password")) { Logger::log("config 相等"); } Logger::log("Finished!"); ``` </details> <br /> 输出 ``` 2020-09-24: Started! 2020-09-24: Logger 相同 2020-09-24: config 相等 2020-09-24: Finished! ```