Welcome 微信登录

首页 / 网页编程 / PHP / PHP实现单件模式的几种方式

PHP实现单件模式的几种方式2011-10-27单件模式是我们在开发中经常用到的一种设计模式,利用PHP5面向对象的特性,我们可以很容易的构建单件模式的应用,下面是单件模式在PHP中的几种实现方法:

class Stat{
static $instance = NULL;

static function getInstance(){
if(self::$instance == NULL){
self::$instance = new Stat();
}

return self::$instance;
}

private function __construct(){
}

private function __clone(){
}

function sayHi(){
return "The Class is saying hi to u ";
}
}

echo Stat::getInstance()->sayHi();

这是一种最通常的方式,在一个getInstance方法中返回唯一的类实例。

对这里例子稍加修改,便可以产生一个通用的方法,只要叫道任何你想用到单件的类里,就可以了。

class Teacher{
function sayHi(){
return "The teacher smiling and said "Hello "";
}

static function getInstance(){
static $instance;

if(!isset($instance)){
$c = __CLASS__;
$instance = new $c;
}

return $instance;
}
}

echo Teacher::getInstance()->sayHi();