试图理解和使用PHP中的OOP我有一个名为dbcon
的类。我正在关注youtube中的教程,该教程使用受保护的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;
}
}
?>
答案 0 :(得分:0)
我首先想到的是,这可能很难进行单元测试。每次从该类中实例创建时,都必须有一个可以连接到的数据库,否则它将失败。
当然,connect()方法仍然很难测试,但是您可以轻松测试其余部分。
有一种技巧可以在一行中调用一个方法并创建一个类的实例:
($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;
}
对不起,懒惰的论点:-)