PHP 如果未启用 mysqli,则不会抛出异常

PHP does not throw exception if mysqli is not enabled

我有

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once "configuration.php";
header('Content-Type: application/json');
try
{   
    $mysqli = new mysqli(MYSQL_SERVER, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);
    $mysqli->set_charset("utf8");
} catch (Exception $e) {
    echo json_encode(
        array(
            'msg' => $e->getMessage()
        )
    );
}

如果 mysqli 未启用,则它不会捕获错误:

Fatal error: Uncaught Error: Class 'mysqli' not found in C:\test\db_connect.php:8
Stack trace:
#0 C:\test\getContacts.php(2): require_once()
#1 {main} thrown in C:\test\db_connect.php on line 8

我该怎么做才能捕获错误?

我试过这个但是没用:

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once "configuration.php";
header('Content-Type: application/json');
try
{
    if(!extension_loaded('mysqli'))
    {
        throw new Exception('mysqli is not enabled');
    }

    $mysqli = new mysqli(MYSQL_SERVER, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DATABASE);
    $mysqli->set_charset("utf8");
} catch (Exception $e) {
    echo json_encode(
        array(
            'msg' => $e->getMessage()
        )
    );
}

这个不停机,继续执行脚本

{"msg":"mysqli is not enabled"}
Notice: Undefined variable: mysqli in C:\test\getContacts.php on line 99

Fatal error: Uncaught Error: Call to a member function query() on null in C:\test\getContacts.php:99 Stack trace: #0 {main} thrown in C:\test\getContacts.php on line 99

奇怪的是,它不会被安装,但如果你自己安装,我想它可以被省略。我会检查程序函数是否存在

if(!function_exists('mysqli_connect')) {
    throw new Exception('mysqli is not enabled');
}

由于问题已标记 php-7:可以捕获 php 7 中的错误,但它不会继承自 Exception,因此您必须以不同的方式捕获它们:

...
} catch (Error $e) {
         ^^^^^ Not Exception
    echo json_encode(
        array(
            'msg' => $e->getMessage()
        )
    );
    // stop execution
    exit;
}

有关 error handling in php 7 的更多信息,请参阅手册。