我在构造函数中为PDO包装器设置了以下PDO初始化:
public function __construct($engine, $host, $username, $password, $dbName)
{
$this->host = $host;
$this->dsn = $engine.':dbname='.$dbName.';host='.$host;
$this->dbh = parent::__construct($this->dsn, $username, $password);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
我的主要问题是当我将dbh设置为在构造函数中初始化为父类时,它返回NULL
。
这会产生连锁反应。
有什么具体的我做错了吗?
答案 0 :(得分:2)
您不理解parent::__construct()
来电。
调用parent::__construct()
不会返回任何内容:
<?php
class Obj {
public $deja;
public function __construct() {
$this->deja = "Constructed";
}
}
$obj = new Obj();
class eObj extends Obj {
public $parent;
public function __construct() {
$this->parent = parent::__construct();
}
}
$eObj = new eObj();
if($eObj->parent==null) {
echo "I'm null";
echo $eObj->deja; // outputs Constructed
}
?>
调用parent::__construct()
只是调用对象上的父构造函数。将设置父级中定义的任何变量,等等。它不会返回任何内容。
答案 1 :(得分:2)
你正在混合包装一个类并继承一个类。
要么这样做(包装):
class YourDB
{
public function __construct($engine, $host, $username, $password, $dbName)
{
$this->host = $host;
$this->dsn = $engine.':dbname='.$dbName.';host='.$host;
// here we are wrapping a PDO instance;
$this->dbh = new PDO($this->dsn, $username, $password);
$this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
// possibly create proxy methods to the wrapped PDO object methods
}
或(继承):
class YourDB
extends PDO // extending PDO, and thus inheriting from it
{
public function __construct($engine, $host, $username, $password, $dbName)
{
$this->host = $host;
$this->dsn = $engine.':dbname='.$dbName.';host='.$host;
// here we are calling the constructor of our inherited class
parent::_construct($this->dsn, $username, $password);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
// possibly override inherited PDO methods
}