话不多说直接上代码
talk is cheap show you the code!
<?php
//创建单例
class Singleton {
// 实例对象
private static $_instance = null;
/**
* 声明一个私有的构造函数,方式通过new来实例化
* 关闭: 通过初始化来实例化对象
*/
private function __construct() {
}
/**
* 获取对象实例
*/
public static function getInstance() {
// 第一次实例化开始时, self::$_instance=null
if (is_null(self::$_instance)) {
// 给实例属性赋值 实例化当前类
self::$_instance = new self();
}
// 第二次实例化时,self::$_instance!=null
return self::$_instance;
}
/**
* 关闭clone对象复制的开关
*/
public function __clone() {
die("单例模式不能克隆");
}
}
获取我们的实例
<?php
Singleton::getInstance(); // 首次初始化(实例化)