日期:2014-05-17  浏览次数:20510 次

PHP中如何实现Singleton(单例模式)

单例模式有以下的特点:

?

  1. 单例类只能有一个实例。
  2. 单例类必须自己创建自己的唯一的实例。
  3. 单例类必须给所有其他对象提供这一实例。

代码:

Singleton.php:

<?php
class Singleton
{
??? private static $instance;

??? private function __construct()
??? {
??? }

??? public static function getInstance()
??? {
??????? if(self::$instance == null)
??????? {
??????????? self::$instance = new Singleton();
??????? }

??????? return self::$instance;
??? }
}
?>

?

在使用的时候,因为构造方法是private(私有)的,所以是不能直接实例化的,必须使用类似下面的方法:

例子:

<?php
require_once('Singleton.php');

$instance = Singleton::getInstance();
?>