2011-12-26 2 views
2

2 클래스를 만들고 1 클래스에서 다른 클래스를 PDO 객체라고합니다. 하지만 그 클래스의 모든 문자열을 참조 할 때 PDO 개체가 아닌 경우. 어떤 아이디어? 여기에 나는 또한 생성자에서 PDO 개체를 만들 수있는 연결 클래스를 수정하고 PDO 개체에 액세스하기위한 getConnection 메소드를 추가 한 내 코드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(); 
    } 
} 

입니다.

생성자에 대해 __construct 키워드를 사용해야하며 클래스 이름이 이전 구문이므로 생성자의 이름을 지정하고 코드를 편집하기가 더 어렵습니다.

마지막으로, 사람에 따라 다르지만 보호 된 개인 속성이나 메서드 앞에 밑줄 _을 추가하는 것이 좋습니다. 이렇게하면 메서드/속성이 클래스 외부에서 액세스 가능한지 쉽게 확인할 수 있습니다. PHP는 대소 문자를 구분하므로 Result과 같은 변수를 사용하지 않아야합니다. Resultresult과 같지 않습니다. 따라서 변수 이름을 소문자로 유지하려면 오타를 피하는 것이 좋습니다 (camelCase를 수행 할 때 appart).

+0

감사합니다. 문제가 해결되어 다시 한번 감사드립니다. – DON