PHP中如何实现Singleton(单例模式)
2009-10-23 文章来源:互联网 浏览次数:1368
分享文章
单例模式有以下的特点:
- 单例类只能有一个实例。
- 单例类必须自己创建自己的唯一的实例。
- 单例类必须给所有其他对象提供这一实例。
代码:
- <?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();
- ?>

文章评论(查看全部)