当我们告诉它不要这样做时,为什么 PDO 会产生警告?

Why PDO generates warnings when we tell it not to do it?

问题

我们告诉 PDO 将每个问题包装到异常中。 在某些情况下,它会生成一些警告,然后才抛出异常。

为什么会这样做?

重复?

SO 上没有关于它的正确答案。最后一个问题是 但人们只是将其标记为重复而不是仔细回答。

已接受的答案未回答为什么以及何时这样做。所以我研究了会回答。

这是因为 PDO 可以使用 mysqlnd 驱动程序,这不符合 PDO 的任何 "convert-issues-to-extensions" 政策。

看看sources of mysqlnd driver.

我们清楚地看到直接调用 php_error_docref

其中一个示例显示在 explained by these lines: https://github.com/php/php-src/blob/PHP-5.5.31/ext/mysqlnd/mysqlnd_wireprotocol.c#L35:L61

使用set_error_handler() 和restore_error_handler()

public function query($sql)
{
    $retries = 0;
    $result = null;

    while (true) {
        try {
            set_error_handler(function () {
            });
            $result = $this->pdo->query($sql);
            restore_error_handler();
            break;
        } catch (Exception $e) {
            restore_error_handler();
            if (++$retries < self::RECONNECT_ATTEMPT) {
                if (strpos($e->getMessage(), 'server has gone away') !== false) {
                    $this->connect();
                    $this->getLogger()->info('Reconnect database, reason: server has gone away');
                }
            } else {
                throw $e;
            }
        }
    }
    return $result;
}