2012-12-03 51 views
-1

我试图创建一个数据库连接类,我的所有模型都将从此扩展而来。不返回来自自定义数据库类的PDO对象

的问题是,是,它没有返回即使我告诉它返回PDO连接对象的数据库对象:

class Database {

protected $conn ; 
public $user ; 
public $pass ; 
public $database ; 
public $encoding ; 

function __construct($user = 'user', $pass = 'pass', $database = 'view4', $host = 'localhost', $encoding = 'UTF8') 
{ 
    try { 
     $this->user = $user ; 
     $this->pass = $pass ; 
     $this->database = $database ; 
     $this->encoding = $encoding ; 

     $options = array(
        'PDO::ATTR_ERRMODE' => 'PDO::ERRMODE_WARNING', 
        'PDO::ATTR_PERSISTENT' => TRUE, 
        'PDO::ATTR_DEFAULT_FETCH_MODE' => 'PDO::FETCH_ASSOC', 
        'PDO::ATTR_EMULATE_PREPARES' => FALSE, 
        ) ; 

     $this->conn = new PDO('mysql:host='.$host.';dbname='.$this->database, 
           $this->user, 
           $this->pass, 
           $options 
          ) ; 
     $this->conn->exec('SET NAMES '.$this->encoding) ; 
     return $this->conn ; 
    } catch(PDOException $e) { 
     $this->handleError($e) ; 
    } 
} 

protected function handleError($e) 
{ 
    if(strstr($e->getMessage(), 'SQLSTATE[')) { 
     preg_match('/SQLSTATE\[(\w+)\] \[(\w+)\] (.*)/', $e->getMessage(), $matches); 
     $code = ($matches[1] == 'HT000' ? $matches[2] : $matches[1]).': '; 
     echo $message = $code.$matches[3] ; 
     return false ; 
    } 
} 

}

它给我的错误:

Fatal error: Call to undefined method Database::query() in C:\xampp\htdocs\IMS4\libs\Database.php on line 52 

我在做什么错了?

+0

你打开服务器上的PDO扩展吗? – vodich

+0

@vodich是的。 – imperium2335

+0

并且数据库 - >查询确实存在?你的错误说未定义的方法 – vodich

回答

2

您不能构造函数return任何东西。在编写new Database时,无论您从构造函数返回什么,您都会得到一个Database对象。

相关问题