Jason OOO
Jason OOO

Reputation: 3552

PDO setAttribute with PDOException

This my function that currently using:

function pdo_connect(){
  try {

      $pdo = new PDO('mysql:host=localhost;dbname='.DB_NAME, DB_USER, DB_PASS);
      $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);     
      $pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );           
      $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

  } catch (PDOException $e) {

      die("Error!: " . $e->getMessage() . "<br/>");

  }

  return $pdo;
}

But consider that I used this

$pdo->setAttribute( INVALID_SYNTAX, false );

I don't want to see fatal error:

Fatal error: Undefined class constant 'INVALID_SYNTAX' in C:\xampp\htdocs\test.php on line 12

I want to catch in exception, then How to do that/?

Upvotes: 1

Views: 1406

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157918

Actually, there is no point in catching development phase errors.

A constant can be undefined only in the development phase. And there is no use in catching it - a developer just have to define it and move on.

Exceptions is one of the most misunderstood mechanisms in PHP. Although they actually have to be used ONLY in case when a recoverable error can be handled somehow, PHP users exploit it in all but proper ways: for the error reporting, data validation or as an error suppression operator.

Upvotes: 1

deceze
deceze

Reputation: 522442

An undefined constant error is not an exception, but a compilation error. It's like a syntax error, it's something that's a fundamental error in your code that needs to be fixed. It doesn't make sense to catch it at runtime. It's also not actually possible.

The constant INVALID_SYNTAX would also never trigger an "undefined class constant" error, only a "plain" undefined constant error.


Exceptions are there to handle exceptional errors during runtime. Exceptional errors are errors that should not happen during normal execution, but you are prepared in case they do.
A mistyped constant is always going to cause an error, and always the same error. It's not exceptional, it's simply wrong code. It therefore makes no sense to want to handle it at runtime dynamically.

Upvotes: 2

Related Questions