php 示例

最后更新于:2022-04-02 04:19:25

[TOC] ## 示例 ### 概念示例
main.php ```
输出 ``` 相等 ``` ### 单例日志与配置 采用单例服用的方式
main.php ``` 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!"); ```

输出 ``` 2020-09-24: Started! 2020-09-24: Logger 相同 2020-09-24: config 相等 2020-09-24: Finished! ```
';