0

There are two classes:

class Db {
    public static function getConnection () {
        /*Initialize parameters*/
        $db = new PDO (...);
        return $db;
    }
}

Class Db initializes and returns a PDO object.

Then I want to do following in another class:

class User {
    private $db = Db::getConnection();
    ....
}

Why am I getting an error here:

private $db = Db::getConnection();
qazerty23
  • 411
  • 2
  • 6
  • 16

1 Answers1

0

Without knowing the error, it's hard to say, but I'd guess is because you can't do that there, try this.

class User {
    private $db = null;

    function __construct(){
        $this->db = Db::getConnection();
    }

    public function getFriends(){
        return $this->db->query('SELECT * FROM friends');
    }
}
TMH
  • 6,096
  • 7
  • 51
  • 88
  • Why not just `private $db;` ? – Dacaspex Jul 12 '16 at 09:33
  • I guess personal preference, I always give a value if I can, although it's not needed. – TMH Jul 12 '16 at 09:34
  • @TomHart If I use this option, $db will be initialized only when I create an object with new operator. But I want to use this $db variable inside my methods in User class. – qazerty23 Jul 12 '16 at 09:37
  • Will `User` just be static methods? Otherwise you'd have to instantiate the object anyway – TMH Jul 12 '16 at 09:41
  • @TomHart No. The `User` class will have methods like `login()`, `getFriends`, etc. Each of these methods makes a SQL query to database, so I would have to have `Db::getConnection()` in each method. So I want a $db property which can be accessed from each method. – qazerty23 Jul 12 '16 at 09:49
  • This will be. In each method, just use `$this->db->yourMethod(...);`. I've added an example method – TMH Jul 12 '16 at 09:52
  • Yeah, this works, thanks @TomHart. Why didn't `private $db = Db::getConnection();` work though? – qazerty23 Jul 12 '16 at 10:04
  • I don't think you can do any functions in a class, outside of a method. So you can't do something like `private $time = time();` it has to be in a method. – TMH Jul 12 '16 at 10:12