單例模式PHP實現代碼

jspet 9年前發布 | 1K 次閱讀 PHP

<?php
class SqlHelper
{
    private static $_instance;
    public $_dbname;
    private function construct()
    {
    }
    //getInstance()方法必須設置為公有的,必須調用此方法
    public static function getInstance()
    {
        //對象方法不能訪問普通的對象屬性,所以$_instance需要設為靜態的
        if (self::$_instance === null) {
            //                self::$_instance=new SqlHelper();//方式一
self::$_instance = new self(); //方式二
} return self::$_instance; } public function getDbName() { echo $this->_dbname; } public function setDbName($dbname) { $this->_dbname = $dbname; } } // $sqlHelper=new SqlHelper();//打印:Fatal error: Call to private SqlHelper::
construct() from invalid context $A = SqlHelper::getInstance(); $A->setDbName('數據庫名'); $A->getDbName(); // unset($A);//移除引用 $B = SqlHelper::getInstance(); $B->getDbName(); $C = SqlHelper::getInstance(); $C->getDbName();

?></pre>

 本文由用戶 jspet 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!