PDO包装返回NULL



我在构造函数中为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

,这会产生连锁反应。

我做错了什么吗?

您混淆了包装类和继承类。

或者这样做(换行):

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
}

您不理解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()只是调用对象的父构造函数。在父类中定义的任何变量都将被设置,等等。它不返回任何东西

最新更新