【问题标题】:PDO Wrapper Returns NULLPDO 包装器返回 NULL
【发布时间】:2011-12-01 02:42:10
【问题描述】:

我在 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

这会产生连锁反应。

有什么具体的我做错了吗?

【问题讨论】:

    标签: php mysql class pdo wrapper


    【解决方案1】:

    您正在混淆包装类和继承类。

    要么这样做(包装):

    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
    
    }
    

    【讨论】:

    • 啊,是的。非常感谢。
    【解决方案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() 只是调用对象的父构造函数。父级中定义的任何变量都会被设置,等等。它不会返回任何东西。

    【讨论】:

      猜你喜欢
      • 2021-05-29
      • 2012-05-03
      • 1970-01-01
      • 2015-10-04
      • 2019-10-18
      • 2014-06-21
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      相关资源
      最近更新 更多