2011-10-05 4 views
0

J'ai l'ensemble PDO Initialisation suivant dans mon constructeur pour un emballage PDO:AOP Wrapper Retourne 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);  
} 

Mon principal problème est que lorsque je mets DHP pour initialiser en tant que parent dans un constructeur, il retourne NULL .

et cela crée une réaction en chaîne.

Y at-il quelque chose de spécifique que je fais mal?

Répondre

2

Vous mélangez l'emballage d'une classe et héritez d'une classe.

Ou faire (emballage):

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 

} 

Ou (héritant):

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

Ahh, oui. Merci beaucoup. – zeboidlund

2

Vous ne comprenez pas l'appel parent::__construct().

appel parent::__construct() ne retourne rien:

<?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 
} 

?> 

Appel parent::__construct() appelle simplement le constructeur parent sur votre objet. Toutes les variables définies dans le parent seront définies, etc. Il ne retourne rien.