我有三个类,每个类在连接到我的数据库时处理不同的功能。具有处理连接
名称的 1 类;带名称的类 2通过向用户 UI提供错误和成功消息,带名称的类 3使用 MySqli 连接从数据库中检索数据并将其传递给 UI。 这和我平时做数据库连接、收集和展示的方式不一样。通常我只是在三个文件中创建了很多函数,并在需要时调用它们。但是我的网站越来越大,越来越复杂,所以我正在重新组织一切。 我当前的问题是,当我在第 3 堂课中创建数据库连接时,它没有抛出我编写的错误。ConnectDB()
MySqli()
MessageOut()
$_SESSION['message']
WebApp()
class ConnectDB {
//Connecting to database
public function connect() {
//connecting to mysql
@$conn = new mysqli(DB_HOST, DB_USERRW, DB_PASSWRW, DB_DBASE);
// check validity of database connection
if (mysqli_connect_errno()) {
return false;
exit();
}
// select the database to use
return $conn;
}
}
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
class WebApp {
protected $db;
function __construct(){
$this->connector = new ConnectDB();
$this->messager = new MessageOut();
try {
$this->db = $this->connector->connect();
if(!$this->db) {
throw new Exception(' Database connection is currently unavailable.');
}
} catch (Exception $e) {
mysqli_report(MYSQLI_REPORT_OFF);
$errors = array();
$message = $e->getMessage();
//populate array with message and divert output to error class functions
array_push($errors, $message);
$this->messager->erroutput($errors);
}
}
}
我将我的 localhost 定义的密码更改为错误的密码并加载了文件,但是即使错误被抑制,错误也会在我的第一堂课的第 10 行给出。这个想法是在使用之前检查连接。
我如何在我的第 3 堂课中得到抛出的错误,给我“数据库连接当前不可用”。信息?
编辑
所以我重新评估了我所做的并try-catch在constructor我的第三节课中设置了一个块,但我知道我得到了一个错误:Fatal error: Uncaught Error: Call to a member function prepare() on null in第 41 行的第三节课使用了数据库连接。
斯蒂芬大帝