tags:

views:

68

answers:

3

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.

+2  A: 

$db should become $this->db.

 public function __construct() {
    $this->db = Database::getInstance('localhost', 'database', 'root', '123456');
}
Lekensteyn
I now get Call to a member function query() on a non-object in Database.class.php
Vinny
@Vinny: You have the same error there... All member variables must be prefixed by `$this->` to be accessed within a method...
ircmaxell
A: 

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.

Michał Rudnicki
I now get Call to a member function query() on a non-object in Database.class.php
Vinny
A: 

You need to assign and reference $pdo as $this->pdo in Database in addition to assigning $db to $this->db in your Users constructor.

Clay Hinson