[英]Extending vs not extending a class in PHP
我是新来的。 下面是尝试与数据库接口的开始。 如果语法不正确,请让我知道,它似乎可以在我的本地主机上运行。
我想我可以输入类Database extends Mysqli
,对吗? 这将使Mysqli的方法可以直接由Database访问,而不是通过类本身创建的实例访问。 那会比我所做的更好吗?
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/>";
}
}
}
}
如果您的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
代替。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.