PDO捕获PDOException错误

时间:2016-10-03 07:00:29

标签: php mysql class pdo

如果连接有效,它的效果很好,但是如果连接失败,似乎PDOException实际上不起作用。捕获完全无法执行。如果失败,则会中断此行$this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);的执行。所以我无法在catch块中获得PDOException。我如何继续这项工作?

<?php

namespace app\Helpers;

use \PDO;

/**
* Core class which exists only once through the application
*
*/
class Core
{
public $dbh; // handle of the db connexion
private static $instance;

// constructor to create a MySQLi instance (="MySQL Improved Extension")
private function __construct()
{

    $db_host = ConfigHelper::read('db.host');
    $db_name = ConfigHelper::read('db.basename');
    $db_user = ConfigHelper::read('db.user');
    $db_pass = ConfigHelper::read('db.password');
    $db_driver = ConfigHelper::read('db.driver');
    try {
        $this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);
    } catch (PDOException $pdoex) {
        exit("Database connection failed: " . $pdoex->getMessage());
        return false;
    }

}
/**
 * get instance of Core object
 *
 * @return Object self
 */
public static function getInstance()
{
    if (!isset(self::$instance)) {
        $object = __CLASS__;
        self::$instance = new $object;
    }
    return self::$instance;
}

}

1 个答案:

答案 0 :(得分:4)

这是命名空间问题。

在命名空间内,您必须通过在反斜杠前面添加每个根级别类名来解决它。

但你没有。

但最糟糕的是你根本不应该抓住PDOException 。只需leave it alone and let it report to a site-wide report handler