PHP的单例模式

PHP的单例模式

1. $_instance 必须声明为静态的私有变量
2. 构造函数和克隆函数必须声明为私有的,这是为了防止外部程序 new 类从而失去单例模式的意义
3. getInstance()方法必须声明为公有的,必须调用此方法以返回唯一实例的一个引用
4. ::操作符只能访问静态变量或静态函数
5. PHP的单例模式是相对而言的,因为PHP的解释运行机制使得每个PHP页面被解释执行后,所有的相关资源都会被回收。

 1 <?php
 2 
 3 class Config 
 4 {
 5     private static $_instance = NULL;
 6     private function __construct() {}
 7     private function __clone() {}
 8 
 9     public static function getInstance() {
10         if (!self::$_instance instanceof self) {
11             echo 'create' . PHP_EOL;
12             self::$_instance = new self;
13         }
14         else {
15             echo 'reuse' . PHP_EOL;
16         }
17         return self::$_instance;
18     }
19 }
20 
21 $inst = Config::getInstance();

 

页面级的单例模式,这种方法无法实现实例一直在内存中(每次页面被执行时,都会重新建立新的对象,在页面执行完毕后都会被清空)。

当一个页面需要多次使用同一资源(例如缓存或者数据库连接等)时候有意义。

 

posted @ 2017-03-29 08:34  XueYanJie  阅读(106)  评论(0编辑  收藏  举报