【发布时间】:2019-06-29 16:45:57
【问题描述】:
试图理解和使用 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;
}
}
?>
【问题讨论】:
-
简而言之,为什么不呢?这是一个设计决定,准确地说是您的决定。您设计 dbconn() 类的方式的优点/缺点将取决于它(需要)如何与应用程序中的其他对象进行通信。如果可以的话,建议您熟悉interface not an implementation 的编码,这将使您的代码更加灵活和面向未来。
-
你不能从构造函数返回值,你通常会设置一个实例变量。