php單例模式(Singleton Pattern)執行個體教程

來源:互聯網
上載者:User
  1. class DatabaseConnection {
  2. private static $db;
  3. private static $_handle = null;
  4. public static function get() {
  5. if ( self::$db == null ){
  6. echo __LINE__;
  7. self::$db = new DatabaseConnection();
  8. }
  9. return self::$_handle;
  10. }
  11. private function __construct() {
  12. $dsn = 'mysql://root:password@localhost/photos';
  13. self::$_handle = 123;
  14. }
  15. }
  16. print( "Handle = ".DatabaseConnection::get()."\n" );
  17. print( "Handle = ".DatabaseConnection::get()."\n" );
  18. ?>
複製代碼

9Handle = 123 Handle = 123 [Finished in 0.1s]

例2,php單例模式。

  1. class DatabaseConnection
  2. {
  3. public static function get()
  4. {
  5. static $db = null;//此處將樣本1的靜態成員變為靜態變數
  6. if ( $db == null ){
  7. echo __LINE__;
  8. $db = new DatabaseConnection();
  9. }
  10. return $db;
  11. }
  12. private $_handle = null;//此處將表示樣本1的靜態去除
  13. private function __construct()
  14. {
  15. $dsn = 'mysql://root:password@localhost/photos';
  16. $this->_handle =123;
  17. }
  18. //此處新增擷取私人成員$_handle的方法
  19. public function handle()
  20. {
  21. return $this->_handle;
  22. }
  23. }
  24. print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
  25. print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
  26. ?>
複製代碼

8Handle = 123 Handle = 123 [Finished in 0.1s] 這兩個樣本個人偏好第二個 四。限度可產生執行個體的個數

  1. class DatabaseConnection {
  2. public static function get($persistent_id=0) {//傳入一個標識
  3. static $db = array();//此處改為數組
  4. if ( !array_key_exists($persistent_id, $db) ) {
  5. echo __LINE__;
  6. $db[$persistent_id] = new DatabaseConnection();
  7. }
  8. return $db[$persistent_id];
  9. }
  10. private $_handle = null;
  11. private function __construct() {
  12. $dsn = 'mysql://root:password@localhost/photos';
  13. $this->_handle =123;
  14. }
  15. //此處新增擷取私人成員$_handle的方法
  16. public function handle() {
  17. return $this->_handle;
  18. }
  19. }
  20. print( "Handle = ".DatabaseConnection::get(1)->handle()."\n" );
  21. print( "Handle = ".DatabaseConnection::get(2)->handle()."\n" );
  22. print( "Handle = ".DatabaseConnection::get(2)->handle()."\n" );
  23. ?>
複製代碼

6Handle = 123 6Handle = 123 Handle = 123 [Finished in 0.1s] 補充,利用static靜態化的方法使我們可以輕鬆地實現php的單例模式。當然也可以使用全域變數儲存,但是這種方法僅適用於較小的應用程式。在較大的應用程式中,應避免使用全域變數,並使用對象和方法訪問資源。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.