シングルトン
概要
そのクラスのインスタンスが1つしか生成されないことを保証することができる。
ロケールやLook&Feelなど、絶対にアプリケーション全体で統一しなければならない仕組みの実装に使用される。
Wikipedia:Singleton パターン
メリット
デメリット
テンプレート
PHP
- class Singleton
- {
- #---------------------------------------
- # property 変数宣言
- #---------------------------------------
- private $app_name = '';
- #---------------------------------------
- # class constructor
- #---------------------------------------
- public function __construct( $app_name )
- {
- $this->app_name = $app_name;
- }
- #---------------------------------------
- # class destructor
- #---------------------------------------
- public function __destruct() {}
- #---------------------------------------
- # method getInstance
- #---------------------------------------
- public static function getInstance( $app_name )
- {
- static $instance;
- if ( $instance === null ) {
- $instance = new self( $app_name );
- }
- return $instance;
- }
- }
Qiita:PHPの静的変数 (static変数) の挙動まとめ
を参考にして、クラス変数を getInstance() の中に閉じ込めている。
ExiZ.org:PHPのシングルトンでコンストラクタ的な動きをする
を参考にして、コンストラクタを機能させている。
ルール
実証していないので、間違っているかも。
- require_once( 'Singleton.php' );
- // 変数、メソッドを呼び出す場合
- Singleton::getInstance()->moge;
- Singleton::getInstance()->yoge();
- // 変数に格納したい場合
- $hoge = Singleton::getInstance();
- $hoge->moge;
- $hoge->yoge();
- // クラス内定数(const)を呼び出す場合
- Singleton::ROGE;
- $hoge::ROGE; // こちらはEclipseでエラーになった