2012-01-24 21 views
0

我有一个被许多其他类继承的抽象类。我想这样做,而不是每次重新实例化(__construct())同一个类,只让它初始化一次,并利用先前继承的类的属性。PHP不允许对象多次实例化

我在我的构建使用此:

function __construct() { 
     self::$_instance =& $this; 

     if (!empty(self::$_instance)) { 
      foreach (self::$_instance as $key => $class) { 
        $this->$key = $class; 
      } 
     } 
} 

这工作 - 那种,我能够得到的属性,并重新分配它们,但在此,我也想打电话给一些其他班级,但只有一次。

有关更好的方法去做这个的任何建议?

+0

入住这里 http://stackoverflow.com/questions/8856755/how-can-i-create-a-singleton-in-php – makriria

+0

入住这里 http://stackoverflow.com/questions/8856755/how-can-i-create-a-singleton-in-php – makriria

+0

起初我以为这是一个注册模式,看到for-each循环。 –

回答

8

那是一个单身构建:

class MyClass { 
    private static $instance = null; 
    private final function __construct() { 
     // 
    } 
    private final function __clone() { } 
    public final function __sleep() { 
     throw new Exception('Serializing of Singletons is not allowed'); 
    } 
    public static function getInstance() { 
     if (self::$instance === null) self::$instance = new self(); 
     return self::$instance; 
    } 
} 

我做的构造和__clone()privatefinal阻碍来自克隆人员和其他直接instanciating它。您可以通过MyClass::getInstance()

得到Singleton实例如果你想要一个抽象基单例类来看看这个:https://github.com/WoltLab/WCF/blob/master/wcfsetup/install/files/lib/system/SingletonFactory.class.php

+0

用于生成'final'方法的+1,并且包含'__clone()',这是我没有想到的。 :-) – FtDRbwLXw6

+0

+1,一个坚如磐石的Singleton类。 –

+0

那么,我的构造函数与我拥有的一样吗?我在哪里使用getInstance()?它仍然调用__construct()几次 – David

1

你指的是Singleton模式:

class Foo { 
    private static $instance; 

    private function __construct() { 
    } 

    public static function getInstance() { 
     if (!isset(static::$instance)) { 
      static::$instance = new static(); 
     } 

     return static::$instance; 
    } 
}