Y's note

Web技術・プロダクトマネジメント・そして経営について

本ブログの更新を停止しており、今後は下記Noteに記載していきます。
https://note.com/yutakikuchi/

Singleton

Singletonパターン

1 外部からインスタンスを生成させない
2 インスタンスをひとつだけ生成を許す
ということを実現するデザインパターン

Singletonクラス

<?php

class singleton {
    private static $instance_ = null;
    private function __construct() {
        echo "make instance \n";
    }   

    public static function getInstance() {
        if( is_null( self::$instance_ ) ) { 
            self::$instance_ = new singleton();
        }   
        return self::$instance_;
    }   

}

client

外部のclientからnewをしようとするとerrorになる。
インスタンスを取得する場合はクラスメソッドのgetInstance()を利用する。

<?php

//error
$instance = new singleton(); //ここはエラーになる。

//success
$instance = singleton::getInstance();