I’m trying to create a database connection class that all my models will extend from.
the problem is, is that it isn’t returning the database object even though I am telling it to return the PDO connection object:
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 ;
}
}
}
It gives me the error:
Fatal error: Call to undefined method Database::query() in C:\xampp\htdocs\IMS4\libs\Database.php on line 52
What am I doing wrong?
You cannot
returnanything from a constructor. When writingnew Database, you get aDatabaseobject, regardless of what you’re returning from the constructor.