Can someone please provide a way to handle the Fatal error: Call to a member function prepare() on a non-object
.
Here is my Scenario:
I have a Singleton Database Class which stores my database details and creates an instance of a PDO object when requested.
I then have the following two classes:
Base class:
namespace lib\translator;
use lib\database as db;
class EntityTranslator {
protected $dbConn;
public function __construct() {
try {
$this->dbConn = db\Database::getInstance();
}
catch(\PDOException $e) {
// do some error logging here
}
}
}
Sub class:
namespace lib\translator;
use lib\entity as entity;
class RequestTranslator extends EntityTranslator {
public function __construct() {
parent::__construct();
}
public function createRequest() {
$request = new entity\Request();
try {
$stmt = $this->dbConn->prepare("CALL createRequest()");
$stmt->execute();
$rowCount = $stmt->rowCount();
if ($rowCount == 1) {
$row = $stmt->fetch(\PDO::FETCH_ASSOC);
// do stuff with the data here
}
return $request;
}
catch (\PDOException $pdoe) {
// do error logging here
}
}
}
Now, I am not wondering why the error occurs. I am trying to handle the very rare case when my database connection is not available and the PDO object instantiation (done via the call to db\Database::getInstance()
) throws an exception, resulting in the variable $dbConn
remaining null
.
I realise, it would be possible to test $dbConn
for null
before using it each time. But As I stated, this should be an exceptionally rare situation and may in fact never occur, so I don't think that checking for null
each time is a smart performance choice.
I would like to be able to add on another catch(\Exception $ex){}
block to handle what is essentially a NullPointerException
(as seen in Java) but PHP does not provide for such an exception. Rather they issue the Fatal error: Call to a member function prepare()
on a non-object.
So what I am looking for, is a way to handle this error, for this situation, without checking for null
each time.
Maybe I have missed the basic concept of error handling in PHP, but I have not been able to find a definitive resource on this topic.
Any suggestions?