2011-12-26 134 views
2

我创建2类并从1类我引用其他类PDO对象。但是,当我引用该类的任何字符串时,而不是在PDO对象时。有任何想法吗? 这是我的代码PHP类引用PDO对象

class Connection 
    { 
     private $dbcc; 
     public function Fn_Db_Conn() 
     { 
      $this->dbcc = new PDO("mysql:host=localhost;dbname=db1;", 
      "root","pass1"); 
      return $this->dbcc; 
     } 
    } 
    class Registration 
    { 
     private $Username; 
     private $dbc; 
     public function Registration($Un) 
     { 
      $this->Username = $Un; 
      $this->dbc = new Connection; 
      $this->dbc->Fn_Db_Conn(); 
     } 
     public function Fn_User_Exist() 
     { 

      $Qry = "SELECT * FROM CMT_Users WHERE [email protected]"; 
      $Result = $this->dbc->prepare($Qry); 
      $Result->bindParam("@Username",$this->Username); 
      $Result->execute(); 
      print $Result->rowCount(); 
     } 
    } 

回答

3
class Connection 
{ 
    private $_dbcc; 
    public function getConnection() 
    { 
     return $this->_dbcc; 
    } 
    public function __construct() 
    { 
     $this->_dbcc = new PDO("mysql:host=localhost;dbname=db1;", 
      "root","pass1"); 
    } 
} 
class Registration 
{ 
    private $_username; 
    private $_dbc; 


    public function __construct($un) 
    { 
     $this->_username = $un; 
     $this->_dbc = new Connection(); 
    } 
    public function Fn_User_Exist() 
    { 

     $qry = "SELECT * FROM CMT_Users WHERE [email protected]"; 
     $result = $this->_dbc->getConnection()->prepare($qry); 
     $result->bindParam("@Username",$this->_username); 
     $result->execute(); 
     print $result->rowCount(); 
    } 
} 

我也修改Connection类来创建在构造函数中PDO对象并增加了一个getConnection方法用于访问PDO对象。

您应该使用__construct关键字作为构造函数,命名构造函数的类名是旧的语法,并且使代码更难编辑。

最后一点,它取决于人,但我更喜欢在下划线_前面加上受保护的私有属性或方法,这样我们可以很容易地识别方法/属性是否可以在类之外访问。您应该使用像Result这样的变量,因为PHP区分大小写,因此Result不等于result,所以最好避免使用拼写错误来保留变量名称的小写字母(当您想要执行camelCase时请使用appart)。

+0

谢谢,它已经解决了,再次感谢那些建议。 – DON 2011-12-26 15:53:29