我们经常采用如下方式定义单列:
- class Singleton {
- private static $instance = NULL;
- /** 不容许直接调用构造函数 */
- private function __construct() {
- }
- /** 不容许深度复制 */
- private function __clone() {
- }
- public static function getInstance() {
- if (NULL === self::$instance) {
- self::$instance = new self();
- }
- return self::$instance;
- }
- }
-
很多人都会记得对深度 copy 的保护,但其实我们却疏忽了一点:
- <?php
- $a = Singleton::getInstance();
- $b = unserialize(serialize($a));
- var_dump($a === $b);
- //bool(false)
-
可见还需要修补,加上对序列化的保护:
- class Singleton {
- private static $instance = NULL;
- /** 不容许直接调用构造函数 */
- private function __construct() {
- }
- /** 不容许深度复制 */
- private function __clone() {
- }
- /** 不容许serialize */
- private function __sleep() {
- }
- /** 不容许unserialize */
- private function __wakeup() {
- }
- public static function getInstance() {
- if (NULL === self::$instance) {
- self::$instance = new self();
- }
- return self::$instance;
- }
- }