php - PDO catch PDOException fails on construction -
i've seen variations of code on 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; } }
the class instantiated $db = new db( $config );
, , works great if connection valid, seems pdoexception
doesn't work if connection fails. catch
totally fails execute $this->myerror(...)
function! instead of useful $e->getmessage()
says "connection failed ... access denied user blah", php fatal error: call member function myerror() on non-object in /.../lib/pdo.class.php on line 16
.
if comment out first line in catch , uncomment echo
, works expected, reporting reason connection error. why message available in catch not in simple myerror
class function?
this post ... php, pdo, , exceptions ... seems applicable, doesn't explain much. catch (pdoexception $e)
obsolete, or dysfunctional under circumstances? how keep work?
the reason being pdo::__construct
creates object
upon successful connection. when call parent constructor , fails object doesn't exist anymore. should use self::myerror()
access error function statically in case.
Comments
Post a Comment