I am trying to write a PDO wrapper but I’m having some problems with the constructor. Ideally, I would like to call the parent’s constructor but, for some reason, that is not working. I tried (to test) to check if creating a new PDO and that does work, which I find most confusing.
Here is my code:
class db extends PDO {
private $dbconn;
public function __construct() {
$dsn = 'mysql:dbname=' . MYSQL_DB . ';host=' . MYSQL_HOST;
$user = MYSQL_USER;
$pw = MYSQL_PW;
try {
$this->dbconn = parent::__construct($dsn, $user, $pw);
$this->dbconn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $this->dbconn;
}
catch(PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();;
}
}
}
It works if I replace the parent:: line with $this->dbconn = new PDO($dsn, $user, $pw);
I believe that the “correct/elegant” way to do it is to use the parent:: syntax so I would like to know why that is not working/how I can fix it. Anyone can help?
Thank you!
That’s not how you use constructors, as they don’t return anything. Try the following instead:
NOTE: You may still run into issues, as your constructor doesn’t accept the same arguments as the PDO constructor. One of the tenets of OOP is that of equivalence, as embodied in the Liskov Substitution Principle, which means that the protocol (public API) of a subclass should be a strict superset of its superclass. The reason this is important is that if the subclass has an API that differs from the one presented by the class it inherits from, then it can’t be used to substitute for the superclass in all cases.
For example, how would you use your subclass to connect to a PostgreSQL database or use a SQLite file instead of using mysql? The PDO superclass can work with all three, along with other database back ends, by virtue of the fact you can pass a DSN in as an argument, but you can’t do that with your subclass.
However, all this is getting into aspects of computer science and is drifting off topic somewhat 😉