单例模式可以分为两种: 1. 饿汉模式 2. 懒汉模式
饿汉模式:PHP不支持(以下是java代码)
public class Singleton{
private static Singleton singleton = new Singleton ();
private Singleton (){}
public Singleton getInstance(){return singletion;}
}
懒汉模式:
<?php
class LazySingleton {
private static $_instance = null;
private function __construct() {}
public static function getInstance() {
if(!isset(self::$_instance)) {
# self::$_instance = new __CLASS__;
self::$_instance = new LazySingleton();
}
return self::$_instance;
}
public function operation() {
echo 'lazy singleton <br>';
}
//防止克隆
public function __clone() {
trigger_error('Clone is not allow.', E_USER_ERROR);
}
}
$singleton = LazySingleton::getInstance();
$singleton->operation();
?>
容易出错的地方: HungerSingleton 不支持饿汉模式,由于PHP中属性只支持 常量初始化,new HungerSingleton() 会出现 T_NEW类型的错误。
self::$_instance = new __CLASS__; __CLASS__ 不能直接这么new 如果需要可以才用 $c = __CLASS__; self::$_instance = new $c; 的形式。
关于线程安全的问题。由于PHP自身不存在多线程,所有采用lazy singleton也就不存在这个问题了。