代码如下:
class SingleModel { //创建单例 private static $instance = null; //提供单例接口 public static function getInstance() { if(self::$instance === null) { self::$instance = new self(); } return self::$instance; } //私有化构造函数 private function __construct() { } //私有化克隆函数 private function __clone() { // TODO: Implement __clone() method. } //私有化反序列重构操作 private function __wakeup() { // TODO: Implement __wakeup() method. } }
应用场景:配置、session、DB、缓存等
本文介绍了使用PHP实现单例模式的方法,通过私有化构造函数、克隆函数及反序列化重构操作确保了类的唯一实例,并提供了获取该实例的静态方法。适用于配置管理、数据库连接等场景。

2385

被折叠的 条评论
为什么被折叠?



