I'm using the PDO MySQL driver in my PHP application, and in one of my models I have this:
public function getAllUsers() {
$this->st = $this->db->query('SELECT name FROM users');
$this->st->setFetchMode(PDO::FETCH_OBJ);
$users = array();
while($row = $this->st->fetch()) {
array_push($users, $row->name);
}
return $users;
}
$this->db
is the database handle inherited from the parent class. The problem is, if for some reason $this->db
isn't a valid database object I get this fatal error:
Call to a member function query() on a non-object
this is to be expected, but to make it easier for my end user I don't want to make them wrap the method in a try-catch block or do any error checking, I'm wondering how I can catch that fatal error and throw an exception instead (the entire application uses exceptions).
Is there some sort of PDO option that makes it only throw exceptions in cases like these?
Edit: re-read and I should add that I have a lot of code wrapped in a try-catch block further up in the inheritance tree, so if this produced an exception instead of a fatal error I would be able to catch it and terminate the application gracefully.