【发布时间】:2014-11-27 11:11:51
【问题描述】:
我有一个连接类,当我__construct 时它会初始化数据库凭据。
当失败时,它会抛出一个异常,即由于文件为空或未设置变量而无法设置凭据。
现在没有设置变量。
但是我仍然可以调用该对象来调用该类中的其他函数,这是我不想要的,因为没有变量这是不可能的。像这样:
$connection = new Connection(); //Causes exception because variables aren't set
$connection->initialize(); //Should not be ran, because the variables aren't set. Application shouldn't continue as well.
$connection->doFurtherThings(); //Which shouldn't be run as well, because the application couldn't go further without a db connection
当我发现异常并且没有让值初始化时,这是什么原因?
public function __construct() {
try {
require "Configuration.php";
$credentials = new Configuration('config.ini'); //Doesn't matter. just sets the configuration file
$credential = $credentials->getItems(); //Gets the items
if (isset($credential['engine'], $credential['host'], $credential['dbname'], $credential['username'], $credential['password'])) {
$this->engine = $credential['engine'];
$this->host = filter_var($credential['host'], FILTER_VALIDATE_IP);
$this->dbname = $credential['dbname'];
$this->username = $credential['username'];
$this->password = $credential['password'];
} else {
throw new Exception("Login credentials aren't not set");
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
我必须自己在catch(Exception) 内die() 应用程序吗?我认为例外是这样做的。
【问题讨论】:
-
所以你不希望 ->getItems 被调用,对吗?
-
@Coulton 不,我不希望应用程序可以走得更远。无法初始化数据库变量时。其中包括我不能打电话给
$connection->initialize() -
如何处理异常由实现者决定,所以不要在构造函数中捕获异常。
-
@AlexandruG。我不明白你的意思,当数据库应该为用户初始化时,它不起作用。该应用程序不应该走得更远。
-
好的,所以将
exit();添加到您的异常中