代码之家  ›  专栏  ›  技术社区  ›  Ross

单粒子失败。在include\u中初始化另一个对象一次(somescript.php)

  •  2
  • Ross  · 技术社区  · 16 年前

    require once 当这些脚本运行并实现Class方法时 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();

    不幸的是,当run创建一个新实例时会发生什么?

    非常感谢

    2 回复  |  直到 16 年前
        1
  •  1
  •   Iacopo    16 年前

    它似乎是一个循环依赖关系: get_shared_instance() 函数调用构造函数,构造函数调用 initiate() 在你的情况下,那就是 settings_by_domain() 在后者内部, 获取共享实例() 再次调用,但您仍在构造函数中,因此静态字段 $shared_instance 尚未实例化。

        2
  •  0
  •   mhughes    16 年前
    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;
    }