我正在尝试创建一个我的模型将扩展的数据库连接类。
问题是,即使我告诉它返回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 ;
}
}
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 ;
}
}
它给了我错误:
}
我做错了什么?
答案 0 :(得分:2)
你不能return
来自构造函数的任何东西。在编写new Database
时,无论您从构造函数返回什么内容,都会得到一个Database
对象。