我有一个连接类,它初始化数据库凭证时,我__construct
它。捕获异常时手动终止应用程序?
无论何时失败,它都会抛出一个异常,即由于文件为空或未设置变量而不能设置凭据。
变量现在不设置。
但我仍然可以调用该对象来调用该类中的其他函数,我不想要,因为这是不可能的,没有变量。就像这样:
$connection = new Connection(); //Causes exception because variables arent set
$connection->initialize(); //Should not be ran, because the variables arent set. Application shouldnt continue aswell.
$connection->doFurtherThings(); //Wich shouldnt be run aswell, because the application couldnt go further without a db connection
,这是什么,而我之所以捕捉到的异常,并没有让值初始化?
public function __construct() {
try {
require "Configuration.php";
$credentials = new Configuration('config.ini'); //Doesnt 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 credential's arent not set");
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
我是不是要die()
应用自己的catch(Exception)
里面?我认为这是一个例外。
所以你不想要 - > getItems被调用,是否正确? – Luke 2014-10-02 12:58:16
@Coulton不,我不希望应用程序可以进一步。当它不可能初始化数据库变量时。包括我不能调用'$ connection-> initialize()' – Bas 2014-10-02 12:59:18
它是实现者如何处理异常的决定,所以不要在构造函数中捕获异常。 – 2014-10-02 12:59:21