您的位置主页 > 编程专区 > Php > PHP中如何实现Singleton(单例模式)

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

2009-10-23    文章来源:互联网    浏览次数:1368     分享文章

 

单例模式有以下的特点:

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

代码:

Singleton.php
  1. <?php
  2. class Singleton
  3. {
  4.     private static $instance
  5.  
  6.     private function __construct()
  7.     {
  8.     } 
  9.  
  10.     public static function getInstance()
  11.     {
  12.         if(self::$instance == null)
  13.         {
  14.             self::$instance = new Singleton();
  15.         } 
  16.  
  17.         return self::$instance;
  18.     }
  19. }
  20. ?> 
  21.  

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

例子:

 
  1. <?php
  2. require_once('Singleton.php');
  3. $instance = Singleton::getInstance();
  4. ?>

文章评论(查看全部)

昵 称 *
电子邮箱 *
网 址      4 + 9 = ?