1,一个为静态的变量
2,一个为private构造函数
3,一个可以访问实例的静态方法
class Instance
{
static public $instance = null;
private function __construct()
{
}
/**
* 单例模式
* @return Instance|null
*/
public static function getInstance()
{
if (!self::$instance){
self::$instance = new self();
}
return self::$instance;
}
public function getName()
{
return '我是单例模式';
}
}
使用时:
class Instance extends BaseController
{
public function index()
{
$name = \Instance::getInstance()->getName();
$name = \Instance::getInstance()->getName();
$name = \Instance::getInstance()->getName();
$name = \Instance::getInstance()->getName();
$name = \Instance::getInstance()->getName();
$name = \Instance::getInstance()->getName();
$name = \Instance::getInstance()->getName();
$name = \Instance::getInstance()->getName();
halt($name);
}
|