<?php
class Singleton {
// 保存类的唯一实例
private static $instance = null;
// 私有构造函数,防止在外部实例化
private function __construct() {
// 初始化代码
}
// 私有克隆方法,防止克隆实例
private function __clone() {
// 禁止克隆
}
// 私有反序列化方法,防止反序列化
private function __wakeup() {
// 禁止反序列化
}
// 获取类的唯一实例
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
// 一个示例方法
public function doSomething() {
echo "Doing something!";
}
}
// 使用单例类
$instance1 = Singleton::getInstance();
$instance1->doSomething();
$instance2 = Singleton::getInstance();
$instance2->doSomething();
// 验证是否是同一个实例
if ($instance1 === $instance2) {
echo "Both instances are the same.";
} else {
echo "Instances are different.";
}
?>