简体   繁体   English

PDO包装器返回NULL

[英]PDO Wrapper Returns NULL

I have the following PDO Initialization set in my constructor for a PDO wrapper: 我在构造函数中为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);      
}

My main problem is that when I set dbh to initialize as a parent in a constructor, it returns NULL . 我的主要问题是,当我将dbh设置为在构造函数中作为父级进行初始化时,它将返回NULL

and that creates a chain reaction. 并造成连锁反应。

Is there anything specific that I'm doing wrong? 我做错了什么吗?

You don't understand the parent::__construct() call. 您不理解parent::__construct()调用。

Calling parent::__construct() doesn't return anything: 调用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
}

?>

Calling parent::__construct() simply calls the parent constructor on your object. 调用parent::__construct()只需在对象上调用父构造函数。 Any variables defined in the parent will be set, etc. It doesn't return anything. 父级中定义的任何变量都将被设置,等等。它不会返回任何内容。

You are mixing up wrapping a class and inheriting a class. 您正在混合包装一个类并继承一个类。

Either do this (wrapping): 这样做(包装):

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

}

Or (inheriting): 或(继承):

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM