十年網(wǎng)站開(kāi)發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶(hù) + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專(zhuān)業(yè)推廣+無(wú)憂售后,網(wǎng)站問(wèn)題一站解決
本篇文章給大家分享的是有關(guān)如何在PHP項(xiàng)目中安全的實(shí)現(xiàn)一個(gè)單例模式,小編覺(jué)得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說(shuō),跟著小編一起來(lái)看看吧。
代碼如下:
class A
{
protected static $_instance = null;
protected function __construct()
{
//disallow new instance
}
protected function __clone(){
//disallow clone
}
public function getInstance()
{
if (self::$_instance === null) {
self::$_instance = new self();
}
return self::$_instance;
}
}
class B extends A
{
protected static $_instance = null;
}
$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);
將__construct方法設(shè)為私有,可以保證這個(gè)類(lèi)不被其他人實(shí)例化。但這種寫(xiě)法一個(gè)顯而易見(jiàn)的問(wèn)題是:代碼不能復(fù)用。比如我們?cè)谝粋€(gè)一個(gè)類(lèi)繼承A:
復(fù)制代碼 代碼如下:
class B extends A
{
protected static $_instance = null;
}
$a = A::getInstance();
$b = B::getInstance();
var_dump($a === $b);
上面的代碼會(huì)輸出:
復(fù)制代碼 代碼如下:
bool(true)
問(wèn)題出在self上,self的引用是在類(lèi)被定義時(shí)就決定的,也就是說(shuō),繼承了B的A,他的self引用仍然指向A。為了解決這個(gè)問(wèn)題,在PHP 5.3中引入了后期靜態(tài)綁定的特性。簡(jiǎn)單說(shuō)是通過(guò)static關(guān)鍵字來(lái)訪問(wèn)靜態(tài)的方法或者變量,與self不同,static的引用是由運(yùn)行時(shí)決定。于是簡(jiǎn)單改寫(xiě)一下我們的代碼,讓單例模式可以復(fù)用。
復(fù)制代碼 代碼如下:
class C
{
protected static $_instance = null;
protected function __construct()
{
}
protected function __clone()
{
//disallow clone
}
public function getInstance()
{
if (static::$_instance === null) {
static::$_instance = new static;
}
return static::$_instance;
}
}
class D extends C
{
protected static $_instance = null;
}
$c = C::getInstance();
$d = D::getInstance();
var_dump($c === $d);
以上代碼輸出:
復(fù)制代碼 代碼如下:
bool(false)
這樣,簡(jiǎn)單的繼承并重新初始化$_instance變量就能實(shí)現(xiàn)單例模式。注意上面的方法只有在PHP 5.3中才能使用,對(duì)于之前版本的PHP,還是老老實(shí)實(shí)為每個(gè)單例類(lèi)寫(xiě)一個(gè)getInstance()方法吧。
以上就是如何在PHP項(xiàng)目中安全的實(shí)現(xiàn)一個(gè)單例模式,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見(jiàn)到或用到的。希望你能通過(guò)這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。