PHP之singleInstance

來源:互聯網
上載者:User

標籤:靜態變數   dump   單例模式   ret   log   構造   儲存   mysq   ons   

 1 <?php 2     //單例:一個類只有一個對象。 3     //限制該類得到更多的對象,只允許產生一個對象。,一個對象就可完成所有對象的功能,目的是為了節約成本。這就是單例模式 4      5     /* 6         function func(){ 7             static $name; //局部靜態變數,根據函數生命週期來進行計算,下次調用會繼續存在, 8         } 9         10         class test{11             static $name; //屬於靜態類屬性。 12         }13 14     */15 16     class MySQLDB{17         //聲明一個靜態變數儲存物件18         private static $_instance;19 20         //聲明構造為私人不讓外界new對象21         private function __construct(){22 23         }24 25         //給定一個類方法不讓讓類外直接通過類名去訪問26         public static function getInstance(){27 28             //判斷對象是否被執行個體化29             if (!isset(static::$_instance)) {30                 //if(! (static::$_instance instanceof static)) //用 對象運輸符號 instanceof做判斷31                 //不存在對象,new一個對象並返回給私人靜態變數32                 static::$_instance = new static;33             }34 35             //返回給靜態變數儲存36             return static::$_instance;37         }38 39         //為了防止外界的複製 把私人魔術方法 40         private function __clone(){41 42         }43     }44 45 46     $dao = MySQLDB::getInstance();47 48     var_dump($dao);49 50     $dao1 = MySQLDB::getInstance();51 52     var_dump($dao1);53 54     // $dao2 = clone $dao;  //運行儲存/**/

 

PHP之singleInstance

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.