-1

我正在尝试创建一个数据库连接类,我的所有模型都将从中扩展。

问题是,即使我告诉它返回 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

我究竟做错了什么?

4

1 回答 1

2

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

于 2012-12-03T11:38:28.780 回答