我一直在努力改进OOP。我正在编写一个数据库类,它将处理通过PDO简单地连接到数据库的问题。现在,我想让它使用不同的变量,如果它是从我的本地主机服务器提供的。
考虑以下代码:
<?php
class Database {
private $host;
private $name;
private $username;
private $password;
public $conn;
if ($_SERVER['SERVER_NAME'] == "localhost") {
$host = "change_to_your_db_host";
$name = "change_to_your_db_name";
$username = "change_to_your_db_username";
$password = "change_to_your_db_password";
}
else {
$host = "change_to_your_db_host";
$name = "change_to_your_db_name";
$username = "change_to_your_db_username";
$password = "change_to_your_db_password";
}
public function connect () {
$this->conn = null;
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}
catch (PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
一般来说,我对类很陌生——我为wayyyy编写纯基于产品执行函数的PHP太久了。
我的问题是:
在这样的类中使用$_SERVER变量很酷吗?
在类中使用该条件语句来确定私有变量可以吗?这个类将包含在我的所有其他脚本中,这些脚本通过我的对象类访问数据库。
有没有更有效的方法来写这篇文章,而不是在发现异常时让它回显?
我只是想确保我在未来的日子里做得很好。我已经写PHP很长时间了,我想彻底摆脱我过时过时的方法。
您应该在类的__construct()
方法中进行条件声明,如下所示:
<?php
class Database {
private $host;
private $name;
private $username;
private $password;
public $conn;
public function __construct()
{
if ($_SERVER['SERVER_NAME'] == "localhost")
{
$this->host = "change_to_your_db_host";
$this->name = "change_to_your_db_name";
$this->username = "change_to_your_db_username";
$this->password = "change_to_your_db_password";
}
else
{
$this->host = "change_to_your_db_host";
$this->name = "change_to_your_db_name";
$this->username = "change_to_your_db_username";
$this->password = "change_to_your_db_password";
}
}
public function connect () {
$this->conn = null;
try {
$conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}
catch (PDOException $exception) {
throw $exception // you can throw again this 'Exception to handle it in your code using the object
}
$this->conn = $conn;
return $this; // you should return $this so you can chain the object methods. Since $con is public, you can still access it
}
}
- 在这样的类中使用$_SERVER变量很酷吗
我看不出为什么不。
- 在类中使用该条件语句来确定私有变量可以吗?这个类将包含在我的所有其他脚本中,这些脚本通过我的对象类访问数据库
根据@MarcB的评论,不,你不能在类的顶层运行代码,只能在方法中运行。
- 有没有更有效的方法来写这篇文章,而不是在发现异常时让它回显
是的,再次抛出它,这样您就可以在最后的代码中使用Database
类来处理它。