如何限制单例类克隆?

时间:2014-08-27 06:54:16

标签: php

我知道如何在php中创建一个单例类。但我感到困惑的是,如果我们能够克隆它,那就浪费了那个类。

我可以知道如何限制单例类克隆吗?请检查以下代码:

class DatabaseConnection {

private static $singleton_instance = null;

private function construct__() {
    // Declaring the constructor as private ensures
    // that this object is not created as a new intance
    // outside of this class.  Therefore you must use the
    // global_instance function to create this object.
}

public static function global_instance() {
    static $singleton_instance = null;
    if($singleton_instance === null) {
        $singleton_instance = new DatabaseConnection();
    }

    return($singleton_instance);
}
}

2 个答案:

答案 0 :(得分:4)

只需将您的函数__clone()设为私有。

private function __clone() { }

如果您尝试访问它,将会抛出致命错误

答案 1 :(得分:1)

有一种__clone()方法可以帮助您防止克隆。

public function __clone()
{
    trigger_error('Cloning forbidden.', E_USER_ERROR);
}