最近看了两种单例模式的定义,分别是:
模式1 :class DBUtil {
function &instance() {
static $object;
if(empty($object)) {
$object = new DBUtil();
}
return $object;
}
function DBUtil(){
echo "DBUtil";
}
}$dbUtil = DBUtil::instance();
模式2:class DBUtil2 { private static $instance = null;
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new DBUtil2();
}
return self::$instance;
} function __construct(){
echo "DBUtil2";
}
}$dbUtil2 = DBUtil2::getInstance();
第二种写法我还是理解的很清楚的,但是对于第一种写法,就有很多的问题:
第一:function &instance (){...}中的&意义何在?
第二:两个构造函数写法的取舍,一个为与类名称相同,一个为固定写法__constructor,个人觉得固定写法比较好
第三:php中类直接调用非静态方法是否流行,还是只是为了保持开源程序兼容更多php低版本的一种写法个人感觉第一种单例模式的写法是为了php的向后兼容,保持开源程序被更多的应用
模式1 :class DBUtil {
function &instance() {
static $object;
if(empty($object)) {
$object = new DBUtil();
}
return $object;
}
function DBUtil(){
echo "DBUtil";
}
}$dbUtil = DBUtil::instance();
模式2:class DBUtil2 { private static $instance = null;
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new DBUtil2();
}
return self::$instance;
} function __construct(){
echo "DBUtil2";
}
}$dbUtil2 = DBUtil2::getInstance();
第二种写法我还是理解的很清楚的,但是对于第一种写法,就有很多的问题:
第一:function &instance (){...}中的&意义何在?
第二:两个构造函数写法的取舍,一个为与类名称相同,一个为固定写法__constructor,个人觉得固定写法比较好
第三:php中类直接调用非静态方法是否流行,还是只是为了保持开源程序兼容更多php低版本的一种写法个人感觉第一种单例模式的写法是为了php的向后兼容,保持开源程序被更多的应用
class DBUtil2 { private static $instance = null;
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new DBUtil2();
}
return self::$instance;
} function __construct(){
echo "DBUtil2";
}
}$a = new DBUtil2();
$b = new DBUtil2();
$c = new DBUtil2();
应为
$dbUtil =& DBUtil::instance();
否则不能实现单例