代码之家  ›  专栏  ›  技术社区  ›  Mona Coder

构造函数应该做的不仅仅是创建一个实例吗?

  •  0
  • Mona Coder  · 技术社区  · 6 年前

    dbcon connect() 函数连接到数据库。现在我的问题是为什么不在构造函数中连接到db?

    function __construct() {
          $this->DBSERVER  = "localhost" 
          $this->DBUSERNAME = "root" 
          $this->DBPASSWORD = "" 
          $this->DBNAME    = "thedb" 
    
          $conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
          if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
          }     
          return $conn;
        } 
        }
    

    <?PHP
    class dbcon {
        private $DBSERVER;
        private $DBUSERNAME;
        private $DBPASSWORD;
        private $DBNAME;
    
        protected function connect(){
          $this->DBSERVER   = "localhost" 
          $this->DBUSERNAME = "root" 
          $this->DBPASSWORD = "" 
          $this->DBNAME     = "thedb" 
    
          $conn = new mysqli($this->DBSERVER, $this->DBUSERNAME, $this->DBPASSWORD, $this->DBNAME);
          if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
          }     
          return $conn;
        }
    }
    ?>
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Mirko Steiner    6 年前

    我的第一个想法是,这可能很难进行单元测试。每次您从该类中创建实例时,必须有一个可以连接到的数据库,否则它将失败。

    调用方法并在一行中创建类的实例有一个技巧:

    ($myDBInstance = new dbcon("localhost", "mirko", "mysecret", "mydb"))->connect();
    

    $myDBInstance = dbcon::getInstanceAndConnect("localhost", "mirko", "mysecret", "mydb");
    

    这可能看起来像:

    public static getInstanceAndConnect(a,b,c,d) {
         $mydbcon=new dbcon(a,b,c,d);
         $mydbcon->connect();
         return $mydbcon;
    }
    

    对于懒惰的争论,我很抱歉:-)

    推荐文章