Creating the Singleton design pattern in PHP5

前端 未结 21 1839
猫巷女王i
猫巷女王i 2020-11-22 04:21

How would one create a Singleton class using PHP5 classes?

21条回答
  •  忘了有多久
    2020-11-22 04:56

    Database class that checks if there is any existing database instance it will return previous instance.

       class Database {  
            public static $instance;  
             public static function getInstance(){  
                if(!isset(Database::$instance) ) {  
                    Database::$instance = new Database();  
                }  
               return Database::$instance;  
             }  
             private function __cunstruct() {  
               /* private and cant create multiple objects */  
             }  
             public function getQuery(){  
                return "Test Query Data";  
             }  
        }  
        $dbObj = Database::getInstance();  
        $dbObj2 = Database::getInstance();  
        var_dump($dbObj);  
        var_dump($dbObj2);  
    
    
    /* 
    After execution you will get following output: 
    
    object(Database)[1] 
    object(Database)[1] 
    
    */  
    

    Ref http://www.phptechi.com/php-singleton-design-patterns-example.html

提交回复
热议问题