The issue resides in the Db class definition. The first time you called conDb
it returned a new Db object that then assigned the static variable a PDO object.
The second time you call that method you get back a PDO object which made the if guard evaluate to false, since a Db object and PDO object are different. In case you call it more than 2 times the objects returned thereafter would be PDO objects and tested for true.
Below a suggested change to the Db class.
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 __clone()
{
}
private function __wakeup()
{
}
public static function conDb()
{
// This is always null the first call
if (is_null(self::$PDO)) {
// Here you returned a new Db object.
// return new self(); // <- old line.
try {
self::$PDO = new PDO($this->dsn, $this->user, $this->password, $this->options);
} catch (PDOexception $e) {
"Date base connection error " . $e->getMessage();
}
}
// Here you returned a PDO object in an else, this can just be the variable after the PDO object is created.
return self::$PDO;
}
}
In the construction of the Model, the if would evaluate to false testing a Db object vs a PDO object.
public function __construct()
{
$this->db2 = Db::conDb();
$this->db = Db::conDb();
if ($this->db == $this->db2) {
echo "Singleton works";
} else {
echo "Fail";
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…