-1

I'm trying to use PDO and so I'm putting it in a getter in my Database class:

class Database {

    // dsn, username and password here

    private $mysql;
    public function __construct(){
        $mysql = new PDO($this->dsn, $this->dbUsername, $this->dbPassword);  
        $mysql->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        $mysql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->mysql = $mysql;
    }

    public function database(){
        return $this->mysql;
    }

}

And I'm calling the database method as such:

class Router extends Database {

    public function loggedin(){

            $query = $this->mysql()->prepare('SELECT * ...');
            $query->execute(array(...));
            ...

}

However I keep getting the following error:

Fatal error: Call to a member function prepare() on a non-object 

I've asked people more knowledgeable than myself about this, however I'm still confused as to why this wouldn't work. Any help and explanation (CS student;- I better understand why) is greatly appreciated!

Thanks!

Patrick
  • 480
  • 3
  • 7
  • 18
  • I was shown a very similar suggestion to this by one of my friends: http://stackoverflow.com/a/13437605/1188214. Is this the best way to go about solving this solution? I believe I still had the same error as the one above when I tried this sln. – Patrick Apr 21 '14 at 22:19
  • Are you aware that in programming `extends` stands for **is a**. What you have defined read as: *"Every router is a database"*. It might be just me, or that sounds a bit mental. And the other thing is: you really shouldn't make a new DB connection for each instance of router. Instead you should inject the PDO instance in the constructor. [This post](http://stackoverflow.com/a/11369679/727208) might give some hints on "how". – tereško Apr 22 '14 at 07:37
  • @tereško Why this particular code doesn't work as intended and why it is poorly designed are two different things. Foor design issues there is nice site here http://codereview.stackexchange.com. Anyway, good comment. –  Apr 22 '14 at 08:14
  • Actually, for "design issues" there is http://programmers.stackexchange.com/ . Why do you think I wrote it as a comment and not as an answer? Or did you think that it was too long for a comment? .. As for this particular question: http://stackoverflow.com/a/12769983/727208 – tereško Apr 22 '14 at 08:18
  • Okay, thanks. Makes a lot more sense now. Love this place :-) – Patrick Apr 22 '14 at 09:19

1 Answers1

2

You are using private access modifier private $mysql;. Change it to protected $mysql;.