I'm receiving the following error message while trying to call a method from a Singleton class, inside another class. Any ideas?
Call to a member function query() on a non-object.
I'm receiving the following error message while trying to call a method from a Singleton class, inside another class. Any ideas?
Call to a member function query() on a non-object.
$db
should become $this->db
.
public function __construct() {
$this->db = Database::getInstance('localhost', 'database', 'root', '123456');
}
Just change $db
in constructor to $this->db
. In PHP member properties are accessed by explicit reference to $this
object.
Also, you have made the same mistake in your Database class. Additionally, specifying method connect() as static does not make much sense. In addition, if you ask me, private
qualifier would be more appropriate than public
. Finally, if you have no intention of handling the exception elsewhere just use die()
instead of echo
.
public function connect($server, $database, $user, $pass) {
try {
$this->pdo = new PDO("mysql:host=$server;dbname=$database", $user, $pass);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Error!";
}
}
In method query()
also use $this->pdo
instead of just $pdo
.
You need to assign and reference $pdo as $this->pdo in Database in addition to assigning $db to $this->db in your Users constructor.