我有一個連接類,它初始化數據庫憑證時,我__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