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!
PDO::__construct()
But not when used in aparent
sense, 'cause you're sort of already inside that object, so it wouldn't make sense to return an instance to itself. – Grishilda(new foo())->method()
should be legal in the 5.4rc1, though. If I remember right – Ause$this->dbconn
, I'd guess that what you suggest is what he's actually thinking. – Grishilda