Suppose I have this:
class Validator {
private $db;
public checkIfUsernameAlreadyExists($username) {
if (!$this->db)
return false;
// Queries
}
}
Assume the $db-object was created in the constructor (or a $db-object was given as a parameter in the constructor).
The problem is that all methods which have to use the $db-object need to check first if this object really exists. A database-connection may fail for several reasons. If it doesn’t exist and no check was made, the script will crash (“method on non-object”-error).
Is there a way to work around this issue? Checking the object in every method doesn’t sound the correct way. Or is it?
Thank you
Checking the object in every method is definitely not right.
The purpose of constructor arguments is to have a valid object to work with after it is instantiated:
So, you validate
$dbonce in the constructor and that’s it. If the database connection fails, then the$dbobject should (and will if it’s PDO) throw an exception which will halt the execution of the method anyway.Note: I’d discourage the use of Singleton pattern or global variables for a lot of reasons that can easily be found on Stack Overflow or Google.