单身人士失败。在include_once(somescript.php)中启动另一个对象

时间:2010-06-28 13:29:42

标签: php oop singleton

我正在使用维基百科的PHP单例。问题是单例有一个通过require once加载和运行其他PHP脚本的方法,当运行这些脚本并实现类方法get_shared_instance时,会启动一个新的单例。为什么是这样?什么是工作?

单身人士(基本形式):

class Controller {

    protected static $shared_instance;

    public static function get_shared_instance()
    {
        if (self::$shared_instance === NULL) { 
            self::$shared_instance = new self();
        } 

        return self::$shared_instance;
    }

/// Constructor made private to be used with singleton.
final protected function __construct(){ $this->initiate(); }

/// Do not allow the clone operation: $x = clone $v;    
final protected function __clone() { }

加载其他文件的单例方法

private function settings_by_domain()
{
    $current_domain = $_SERVER['HTTP_HOST'];
    $path = pathinfo(__FILE__, $options = PATHINFO_DIRNAME);
    $settings_file = $path.'/'.$current_domain.'.php';

    if (is_file($settings_file))
    {
        $this->settings_file = $settings_file;
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

所需文件包含:

$c = self::get_shared_instance();

,不幸的是,运行时会创建一个新实例吗?

非常感谢 罗斯

2 个答案:

答案 0 :(得分:1)

它似乎是一个循环依赖:get_shared_instance()函数调用构造函数,它调用initiate(),在这种情况下调用settings_by_domain()。 在后者内部,再次调用get_shared_instance(),但您仍然在构造函数中,因此静态字段$shared_instance尚未实例化。

如果没有所有代码,很难提出解决方案,但我建议你检查各种类的相互依赖关系并尝试合理化它。毕竟,为什么单例依赖于需要单例本身才能工作的文件?

答案 1 :(得分:0)

class Controller {

protected static $shared_instance;

public static function get_shared_instance()
{
    if (self::$shared_instance === NULL) { 
    self::$shared_instance = new self();
} 

return self::$shared_instance;

}

课堂范围内的回报?这是完全错误的。它应该是:

class Controller {

protected static $shared_instance;

public static function get_shared_instance()
{
    if (self::$shared_instance === NULL) { 
    self::$shared_instance = new self();
    return self::$shared_instance;
} 

}