连接循环的最佳方式

I am relatively new to OOP and am now trying to adapt my website to githibs's Safemysql https://github.com/colshrapnel/safemysql

I just ran into a riddle that I have to solve out before proceeding in writing more code based on OOP.

On my website I have an admin section where I query different listings for my database users. My first attempt for the User class was

class User {
    function __construct($user_id) {
        $this->dbs  = new SafeMySQL(); 
        $this->user = $this->dbs->getRow('SELECT * FROM users WHERE id = ?i', $user_id);
    }
    function get_something_else() { }
    function calculate_this() { }
}

foreach (array as $user_id) {
    $user = new User($user_id);
}    

Using this first method tells me that if I have a page of hundreads of results I will just create as many connections so I thought of two more ways to use my user class:

class User {
    function __construct() {
        $this->dbs = new SafeMySQL(); 
    }
    function load_user($user_id) {
        $this->user = $this->dbs->getRow('SELECT * FROM users WHERE id = ?i',$user_id);
        $return $this->user
    }
    function get_something_else() { }
    function calculate_this() { }
}

$data = new User();

foreach (array as $user_id) {
    $user = data->load_user($user_id);
}

I had no problem using this class but I keep thinking that by mistake I would define a variable that would persist for another user.

One more alternative I thought about was defining my connection and then using it into a class like this $user = new User($user_id, $connection) but now it just doesn't look neat.

Now I find out about global connection and persistent connection but some do not recommend them.

What would be the best way for writing my user class?

I think the best method is to create a database connection in the page that requires it, then pass it as a variable to the constructor of the user class for it to use. I realize you have tried this already, but this is best method.

Example:

index.php

$dbs = new SafeMySQL();
$user = new User($dbs, 1);

User.php

class User {
      function __construct($dbs, $user_id){
          $this->dbs = $dbs;
          $this->user = $this->dbs->getRow('SELECT * FROM users WHERE id = ?i',$user_id);
       }
}

The idea you had about including your connection in the constructor parameters is I think a good one. The concept is called "dependency injection". The purpose of dependency injection is to decouple your DBMS from your Application Logic, so that if someday you decide not to use SafeMySQL, you can pass in a different connection without changes to your User class (you will need to write an interface around the SafeMySQL class to accomplish that). In this case it has the added benefit of letting you manage your connection to the DBMS independant of your Application Logic.