i have two classes in my project. Db.php :
<?php
namespace appcore;
use PDO;
class Db
{
private $dsn = 'mysql:host=localhost;dbname=test';
private $user = 'root';
private $password = '6ReA4';
private $options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
];
private static $PDO = null;
private function __construct()
{
try {
self::$PDO = new PDO($this->dsn,$this->user,$this->password, $this->options);
} catch (PDOexception $e) {
/* Exception of datebase connection (error message in future) */
echo "Date base connection error ".$e->getMessage();
}
}
private function __clone() {}
private function __wakeup () {}
public static function conDb()
{
if (is_null(self::$PDO)) {
return new self();
} else { return self::$PDO; }
}
}
and Model.php
<?php
namespace appcore;
class Model
{
private $db;
private $db2;
public function __construct()
{
$this->db2 = Db::conDb();
$this->db = Db::conDb();
if ($this->db == $this->db2) {
echo "Singleton works";
} else { echo "Fail"; }
}
public function getById()
{
}
public function getAll()
{
}
}
private $db;
private $db2;
public function __construct()
{
$this->db2 = Db::conDb();
$this->db = Db::conDb();
if ($this->db == $this->db2) {
echo "Singleton works";
} else { echo "Fail"; }
}
public function getById()
{
}
public function getAll()
{
}
}
I'm trying to realize singleton pattern but method conDb() during the Model object creation returns an empty object a second time instead of the same one. Please help me to understand what is the problem and how can i solve this? What am i doing wrong?