Php面向对象 – 单例模式
2024-11-25 22:27:36
在 PHP 中,单例模式确保一个类只有一个实例存在。以下是一个简单的单例模式示例:
<?php
class Singleton {
private static $instance;
private function __construct() {}
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone() {}
}
// 使用示例
$singleton1 = Singleton::getInstance();
$singleton2 = Singleton::getInstance();
if ($singleton1 === $singleton2) {
echo "单例模式成功";
}
?>