Calling PDO::setAttribute within namespaces
I want to use the built-in PDO class to connect to a mysql database.
If I understand it right, the PDO methods don't throw exceptions by default. Is this correct?
So I try to change the error mode:
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
My problem is that I'm using namespaces in my classes so I have to write:
$pdo = new PDO($dsn, $user, $password);
But I don't know how to set the error mode in this context.
$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Same way you declare it initially, my friend!
Remember, PDO
in itself is the class, whether you are declare a new instance ( new PDO
), or if you're referencing static constants ( PDO::ATTR_ERRMODE
). Since you're within a namespace, you must preface it with . This applies to every occurrence of
PDO
, it's all the same class. So we use PDO
throughout.
That can be tricky to remember, you can also just put use PDO;
at the top, and then use PDO
normally throughout. Pick one, and stick with it everywhere.