2011-12-26 49 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