0

Code

connect.php

$username   = "USERNAME";
$password   = "PASSWORD";
$hostname   = "HOSTNAME";
$dbname     = 'DATABASE';

try { $dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password); }

catch(PDOException $e){ echo($e->getMessage()); }

users.php

include "/connect.php";

class User
{   
    private $id, $name1, $name2, $email, $pic, $league_id;

    //Constructor
    public function __construct($id)
    {
        $stmt = $dbh->prepare("SELECT * FROM `users` WHERE `id`=?");
        $stmt->execute(array($id));
        if($stmt->rowCount()<1) exit("Could not find user");
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        $this->id = $row["id"];
        $this->name1 = $row["name1"];
        $this->name2 = $row["name2"];
        $this->pic = $row["pic"];
        $this->league_id = $row["league_id"];
    }

    //functions - Get
    public function getId() { return $this->id; }
    public function getName1(){ return $this->name1; }
    public function getName2(){ return $this->name2; }
    public function getFullName() { return $this->name1 . " " . $this->name2; }
    public function getPic(){ return $this->pic; }
    public function getLeagueId(){ return $this->league_id; }
}

index.php

if(isLoggedIn()) {
    $user = new User($_SESSION["userid"]);
    echo "Welcome back, ".$user->getFullName()."!";
}

Issue

I'm new to classes and OOP in PHP so apologies for the code.

I connect to the database in connect.php, however I'm having difficulty processing queries in the __constructor function.

I understand that I cannot include the connection in the constructor. I also see that the code works if I directly insert the code from connect.php into the function.

However, I don't want to have to connect to the database each time I want to make a query; is there a method for me to connect outside of the __construct function?

As far as being a duplicate, the linked question does not answer this one. My question is: "How can I access the object in /connect.php in the __construct function of my object?"

Ben
  • 8,894
  • 7
  • 44
  • 80
  • The duplicate gives pretty clear options: `global` (no no!), or passing it as a parameter. Or `include` the file inside your constructor; I have no idea why you think that's not possible. – deceze Sep 15 '15 at 15:46
  • Pass object variable to class scope or use global – Abyss Sep 15 '15 at 15:46
  • Re now-deleted-comment: Exactly. You may want to read [this](http://kunststube.net/static), which illuminates a bit why. Since this can arguably get tedious, your class structure can be improved a lot. You'd generally want one "repository" class which you instantiate once and which gets a database connection once, and this repository can then instantiate and return User objects to you. – deceze Sep 15 '15 at 15:50
  • @deceze It doesn't work when I `include` the file, that's why I think it's not possible... – Ben Sep 15 '15 at 15:50
  • You can put `global $dbh;` at the top of `__construct`. But I would suggest wrapping the `$dbh` var in a static class. Ex connect.php: `class Connect { static public $dbh; } Connect::$dbh = new PDO(.....);` Then to use it, `Connect::$dbh->prepare(...);`. Using global variables is an astoundingly bad idea. I did it for a long time and it just made my code terrible. Wrapping it in a class makes it easily accessible anywhere and keeps it neat and organized. – Reed Sep 15 '15 at 15:50
  • @Jakar FYI: `static public` variables are essentially the same as global variables! Read [this](http://kunststube.net/static). – deceze Sep 15 '15 at 15:53
  • @Ben It's perfectly possible to `include` files within functions, including object constructors. – deceze Sep 15 '15 at 16:06
  • @deceze, good read. It is essentially a global variable, but `ClassName::$var` provides a lot more opportunity, usability, and readability than `global $var`. Plus, I'm suggesting that the initialization of the static property be immediately after the class definition (in the same file), and any error handling (of the connection) would be immediately after that. Thus, if `Connect` is available, then it is guaranteed that `Connect::$dbh` is available, and changing the database type only requires changing the database initialization, which is in `connect.php`. – Reed Sep 15 '15 at 16:20
  • Though, i realize my suggestion is imperfect and definitely not the most proper OOP. It's simple though and far better than `global $var`. But yeah. static public variables definitely can cause ridiculous pains sometimes, if not planned for appropriately. – Reed Sep 15 '15 at 16:23
  • 1
    @Jakar Really, everything you just said about static class variables can equally be done with global variables. "If `global $foo` is available, it's guaranteed to be initialized." Just the syntax is different. – deceze Sep 15 '15 at 17:35

0 Answers0