This might not be a real problem at all, but I would like to know why this works.
The code is working the way I posted it here.
I've got a Database() class like this:
class Database extends PDO
{
public function __construct()
{
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING);
parent::__construct(DB_TYPE . ':host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8', DB_USER, DB_PASS, $options);
}
}
This class gets called through the Controller:
class Controller
{
function __construct()
{
Session::init();
if (!isset($_SESSION['user_logged_in']) && isset($_COOKIE['rememberme'])) {
header('location: ' . URL . 'login/loginWithCookie');
}
try {
$this->db = new Database();
} catch (PDOException $e) {
die('Database connection could not be established.');
}
$this->view = new View();
}
}
Notice the Database() class gets called here.
Now, I've got a "model", which needs the database connection to communicate with the database:
class Notes extends Controller
{
public function __construct()
{
parent::__construct();
}
public static function getSumNotes()
{
$sql = "SELECT COUNT(*) FROM table WHERE user_id = :user_id";
$query = new Database();
$query = $query->prepare($sql);
$query->execute(array(':user_id' => $_SESSION['user_id']));
return $query->fetchColumn();
}
}
The thing that irritates me: the method Notes::getSumNotes() calls another new Database() class which is necessary to get my values from the table. Without this the connection would not work.
Question: Why do I have to call the Database() class twice although parent::__construct() from Notes gets the same variables and constructor from the "dads" (Controller) class?
Hope to get enlightened.
Thanks.