PHP實現單例模式

ImClive發表於2018-10-29
<?php
/**
* 單例模式實現
*/
class Singleton
{
    //靜態變數儲存全域性例項
    private static $instance = null;

    private function __clone()
    {
        //私有建構函式,防止外界例項化物件
    }

    private function __construct()
    {
        //私有克隆函式,防止外界克隆物件
    }

    //靜態方法,單例統一訪問入口
    public static function getInstance()
    {
        if (self::$instance instanceof Singleton) {
            echo "return exist instance
";
            return self::$instance;
        }
        self::$instance = new Singleton();
        echo "return new instance
";
        return self::$instance;
    }
}

$a = Singleton::getInstance();//output: return new instance
$a = Singleton::getInstance();//output: return exist instance

相關文章