2012-01-24 30 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; 
    } 
}