单例模式主要使用于数据库的连接, 确保数据库一个类只有一个实例, 并且向整个系统提供这个实例。从而避免new操作消耗资源, 同时避免数据库出现too many connection信息.
要点有三个: 1. 必须只有一个实例。 2. 必须自动创建这个实例。 3. 必须向整个系统提供这个实例。
复制代码 代码如下:
<?
class mysql{
privete static $instance ;//保存实例
//构造函数声明为private, 防止直接创建对象
privete function __construct(){
// 实例化
}
//单例方法, 判断是否已经实例化,只实例化一次
public static function getInstance (){
if(!isset( self::$instance )){
self ::$instance = new self();
}
return self:: $instance;
}
//防止克隆对象
private function __clone (){
trigger_error ("not allow to clone.");
}
function test(){
echo "test" ;
}
}
$conn = mysql::getInstance ();
$conn->test ();
?>
<?
class mysql{
privete static $instance ;//保存实例
//构造函数声明为private, 防止直接创建对象
privete function __construct(){
// 实例化
}
//单例方法, 判断是否已经实例化,只实例化一次
public static function getInstance (){
if(!isset( self::$instance )){
self ::$instance = new self();
}
return self:: $instance;
}
//防止克隆对象
private function __clone (){
trigger_error ("not allow to clone.");
}
function test(){
echo "test" ;
}
}
$conn = mysql::getInstance ();
$conn->test ();
?>
相关文章
猜你喜欢
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10