问题描述
我已经看到这个代码的变化,包括许多S.O。帖子:
I've seen variations of this code all over the place, including many S.O. posts:
class db extends PDO {
public function __construct( $dbconf ) {
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_PERSISTENT => $dbconf['persist'] ? true : false
);
try {
parent::__construct('mysql:host='. $dbconf['dbhost'] .';port=3306;dbname='. $dbconf['dbname'] .';' , $dbconf['dbuser'],
$dbconf['dbpass'],
$options);
} catch (PDOException $e) {
$this->myerror( $e->getMessage() );
// echo 'Connection failed ... '. $e->getMessage();
}
}
...
private function myerror( $error ) {
echo 'Connection failed ... '. $error;
}
}
类实例化为 $ db = new db($ config);
,如果连接有效,它工作的很好,但看起来 PDOException
如果连接失败,实际工作。 catch
完全无法执行 $ this-> myerror(...)
function!而不是有用的 $ e-> getMessage()
说连接失败...访问被拒绝用户blah,我得到一个 PHP致命错误:在第16行上的/.../lib/pdo.class.php中的非对象上调用成员函数myerror()
。
The class is instantiated with $db = new db( $config );
, and it works great if the connection is valid, but it seems PDOException
doesn't actually work if the connection fails. The catch
totally fails to execute the $this->myerror(...)
function! Instead of the useful $e->getMessage()
that says "Connection failed ... Access denied for user blah", I get a PHP Fatal error: Call to a member function myerror() on a non-object in /.../lib/pdo.class.php on line 16
.
如果我注释掉catch中的第一行并取消注释 echo
,它会按预期工作,报告连接错误的原因。为什么消息在catch中可用,但不在简单的 myerror
类函数中?
If I comment out the first line in the catch and uncomment the echo
, it works as expected, reporting the reason for the connection error. Why would the message be available in the catch but not in the simple myerror
class function?
。似乎适用,但没有解释多少。在某些情况下是 catch(PDOException $ e)
是否过时或功能不正常?
This post ... PHP, PDO, and Exceptions ... seems applicable, but doesn't explain much. Is catch (PDOException $e)
obsolete, or dysfunctional under certain circumstances? How do I keep get this to work?
推荐答案
原因是 PDO :: __ construct
The reason being is
PDO::__construct
only creates the object
upon successful connection. So when you call the parent constructor and it fails your object doesn't exist anymore. You should use self::myerror()
to access the error function statically in this case.
这篇关于PDO捕获PDOException构建失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!