我是新来的下面是尝试与数据库接口的开始。如果语法不正确,请告诉我,它似乎适用于我的本地主机。
我想我可以输入Database extends Mysqli类,对吗?这样就可以让数据库直接访问Mysqli的方法,而不是通过类本身创建的实例。这会比我所做的更好吗?
class Database {
#The variable that stores the database handle
public $db;
#The Database objects's datbase parameters
public $host;
public $user;
public $password;
public $database;
#creates a Database object with the required databases details
public function __construct($host, $user, $password, $database) {
$this->host = $host;
$this->user = $user;
$this->password = $password;
$this->database = $database;
}
#Stores the database handle as a var $db of the Database instance
public function connect() {
if ($this->db = new Mysqli($this->host, $this->user, $this->password, $this->database)) {
if ($this->db->connect_errno) {
echo "No connection could be made <br/>";
} else {
echo "database succesfully connected <br/>";
}
}
}
}发布于 2014-05-04 06:56:54
如果您的class Database表示数据库句柄,那么它不应该公开:
#The variable that stores the database handle
public $db;否则,您将不会封装该细节,因此您将根本不需要您的类。
接下来,当您开始编写类时,echo不属于那里:
if ($this->db = new Mysqli($this->host, $this->user, $this->password, $this->database)) {
if ($this->db->connect_errno) {
echo "No connection could be made <br/>";
} else {
echo "database succesfully connected <br/>";
}
}因为类由通过返回值而不是通过标准输出返回的方法组成。相反,您想在这里抛出一个异常。这也是Mysqli的一个特性,因此,您不需要编写自己的错误处理代码就可以开始:
在消除了这些或多或少显而易见的问题之后,您会问自己是否应该继承mysqli而不是聚合它。
其实我不能告诉你。到目前为止,您共享的代码只是显示了mysqli的标准功能,因此我建议完全删除该类,因为代码看起来是多余的。所以我想说:两者都不是。我认为您没有理由使用Database类,因为您只需要使用mysqli。
https://stackoverflow.com/questions/23453443
复制相似问题