Thought I understood how classes work, then I tried this code:
class user
{
var $dbcon;
var $dbinfo;
var $con;
var $error;
function dbConnect()
{
$this->dbinfo['server'] = "localhost";
$this->dbinfo['database'] = "foolish_faith";
$this->dbinfo['user'] = "user";
$this->dbinfo['password'] = "password";
$this->con = "mysql:host=".$dbinfo['server']."; dbname=".$dbinfo['database'];
$this->dbcon = new PDO($con, $dbinfo['user'], $dbinfo['password']);
$this->dbcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->error = $this->dbcon->errorInfo();
if ($error[0] != "")
{
print "Error!";
print_r($error);
}
}
}
Now it just spits out this error:
Fatal error: Uncaught exception
‘PDOException’ with message ‘invalid
data source name’ in
E:\PortableApps\xampp\htdocs\dbcon.php:24
Stack trace: #0
E:\PortableApps\xampp\htdocs\dbcon.php(24):
PDO->__construct(”, NULL, NULL) #1
E:\PortableApps\xampp\htdocs\login.php(4):
user->dbConnect() #2 {main} thrown in
E:\PortableApps\xampp\htdocs\dbcon.php
on line 24
Can anybody see what I’m doing wrong, as I’m sure it has to do with my lack of knowledge when it comes to classes?
When you acces variables of a class instance you have to use the -> operator. In this case you’d use
$this->dbinfoinstead of just$dbinfoand$this->coninstead of$con. You’ve done it correctly on the left side, but missed some on the right.