2011-10-05 75 views
0

我在構造函數中的下列PDO初始化設置了PDO包裝:PDO包裝返回NULL

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);  
} 

我的主要問題是,當我設置胸徑初始化爲在構造函數中父,它返回NULL

並且產生連鎖反應。

有什麼具體的,我做錯了嗎?

回答

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 

} 
+0

啊,是的。非常感謝你。 – zeboidlund

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()只是調用您的對象的父類的構造。父母中定義的任何變量都將被設置,等等。它不返回任何東西。