爲什麼要使用PHP單例模式?
1、PHP的應用主要在於數據庫應用, 所以一個應用中會存在大量的數據庫操作, 使用單例模式, 則可以避免大量的new 操作消耗的資源。
2、如果系統中需要有一個類來全局控制某些配置信息, 那麼使用單例模式可以很方便的實現. 這個可以參看ZF的FrontController部分。
3、在一次頁面請求中, 便於進行調試, 因爲所有的代碼(例如數據庫操作類db)都集中在一個類中, 我們可以在類中設置鉤子, 輸出日誌,從而避免到處var_dump, echo。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
<?php header( "Content-Type:
text/html; charset=UTF-8" ); class Singleton{ //保存類的實例 private static $_instance ; private function __construct(){ echo "This
is a Constructed method;" ; } //防止對象被克隆 public function __clone(){ trigger_error( 'Clone
is not allow !' ,E_USER_ERROR); } public static function getInstance(){ if (!(self:: $_instance instanceof self)){ self:: $_instance = new self; } return self:: $_instance ; } public function test(){ echo '調用方法成功' ; } } //正確的調用方法 $singleton =
Singleton::getInstance(); $singleton ->test(); $singleton_clone = clone $singleton ; ?> |