PHP: Database Connection Class Constructor Method

前端 未结 6 1016
旧巷少年郎
旧巷少年郎 2021-02-03 16:19

I\'m new to OOP. Originally I was defining variables and assigning values to them within the class and outside of the constructor, but after an OOP lesson in Java today, I was t

6条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-03 17:01

    Here is mine and it works rather well:

    class Database
    {
       private static $_dbUser = 'user';
       private static $_dbPass = 'pwd';
       private static $_dbDB = 'dbname';
       private static $_dbHost = 'localhost';
       private static $_connection = NULL;
    
       /**
        * Constructor
        * prevents new Object creation
        */
    
       private function __construct(){
       }
    
       /**
        * Get Database connection
        * 
        * @return Mysqli
        */
    
       public static function getConnection() {
          if (!self::$_connection) {
         self::$_connection = @new mysqli(self::$_dbHost, self::$_dbUser, self::$_dbPass, self::$_dbDB);
    
             if (self::$_connection -> connect_error) {
                die('Connect Error: ' . self::$_connection->connect_error);
             }
          }
          return self::$_connection;
       }
    }
    

    By making the __construct empty, it prevents a new class being instantiated from anywhere. Then, make the function static so now all I need to do to get my connection is Database::getConnection() And this is all in an include file, in a password protected folder on the server and just included with each class file. This will also check to see if a connection is already open before attempting another one. If one is already established, it passes the open connection to the method.

提交回复
热议问题