Explained what I'm doing in the comments:
class User {
public $id;
public $email;
public $username;
public $password;
public $rep;
public function __constructor($id, $email, $username, $password, $rep) { // Assign all 'required' fields for our object upon instantiation
$this->id = $id;
$this->email = $email;
$this->username = $username;
$this->password = $password;
$this->rep = $rep;
}
public static function getUsers($query, $mysqli) { // Pass the query to select desired users and the mysqli connection object
$all_users = $mysqli->query($query);
$user = array();
while($users = $all_users->fetch_assoc()) {
$temp_user = new User($users['id'], $users['email'], $users['username'], $users['password'], $users['rep']);
$user[] = $temp_user;
}
return $user;
}
}
Which allows me to do something like this:
$users = User::getUsers("SELECT * FROM users", $mysqli); // Returns an array of user objects containing each users details
Which I can loop through at will.
Is using a static function like this a good idea? What might be the pitfalls to my design? One that just occurred to me when writing this is that I might not always needs every user field, but it wouldn't be hard to customize the constructor to allow only desired fields to be assigned values.
Here is what I was doing BEFORE the previous example. Is this technically better? The thing that was bothering me is there are several occasions where I'm duplicating the block of code below to instantiate an array of objects. Should I create another class to take care of this process, or am I still going about this the wrong way?
$all_users = $mysqli->query($query);
$user = array();
while($users = $all_users->fetch_assoc()) {
$temp_user = new User($users['id'], $users['email'], $users['username'], $users['password'], $users['rep']);
$user[] = $temp_user;
}
class User {
private $id;
private $email;
private $username;
private $password;
private $rep;
public function __constructor($id, $email, $username, $password, $rep) { // Assign all 'required' fields for our object upon instantiation
$this->id = $id;
$this->email = $email;
$this->username = $username;
$this->password = $password;
$this->rep = $rep;
}
public function getID() {
// etc
}
public function setPassword($password) {
// etc
}
}