2012-01-24 1 views
0

私は抽象クラスを他の多くのクラスに継承しています。私は同じクラスを毎回再インスタンス化(__construct())する代わりに、一度だけ初期化し、以前継承したクラスのプロパティを利用するようにしたいと思います。PHPオブジェクトを複数回インスタンス化できないようにする

私は私の構文でこれを使用しています:これは動作します

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

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

- ソートの、私はプロパティを取得し、それらを再割り当てすることはできんだけど、この中に、私はまた、いくつかを呼び出したいです他の授業は1回だけです。

これを行うより良い方法についてのご意見はありますか?シングルトンザッツ

+0

チェック をあなたは抽象ベース・シングルトンクラスをしたい場合は、このを見てMyClass::getInstance()

を経由してシングルトンのインスタンスを取得することができます 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; 
    } 
} 

私はクローニングおよびそれを直接instanciatingから人々を妨げるために、コンストラクタと__clone()privatefinalを作りました。 https://github.com/WoltLab/WCF/blob/master/wcfsetup/install/files/lib/system/SingletonFactory.class.php

+0

+1のメソッドを 'final'にし、' __clone() 'を含めて考えました。 :-) – FtDRbwLXw6

+0

+1、ロックソリッドシングルトンクラス。 –

+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; 
    } 
}