将OOP PHP与MySQLi对象绑定的典型方法是什么?


What's the typical way to tie in OOP PHP with a MySQLi object?

我已经在程序上使用PHP多年了,但我决定真正与时俱进,开始练习OOP。

假设我有如下所示的内容:

<?php
$db = new mysqli(host, user, pass, db);
class user {
      public $username;
      public function __construct($ID) {
             $sql_query = "SELECT `username` FROM `users` WHERE `userid`='$ID'";
             // execute that query somehow, store result in $result.
             $this->username = $result;
      }
}
$some_user = new user(1);

(我知道查询需要转义等,我只是想举一个基本的例子)

我的主要问题是与类中的$db对象交互的最佳方式是什么?我会打电话给$db->query($sql_query);$db无法访问。很多谷歌搜索都没有给我一个可靠的答案,但我看到了很多将$db对象传递到构造函数中的建议,例如:

 $some_user = new user(1, $db);

我将其理解为"数据注入"是否正确?似乎必须有比将其显式包含在每个构造函数中更好的方法。当然,我总是可以在每个类中创建$db,但重复连接到数据库似乎也没有必要。

//this seems to happen in the global scope, so $db isn't accessible in class user yet    
$db = new mysqli(host, user, pass, db);
class user {
  public $username;
  //to make global $db accessible, pass a reference to user's constructor:
  public function __construct($ID,&$db) {
         $sql_query = "SELECT `username` FROM `users` WHERE `userid`='$ID'";
         // execute that query somehow, store result in $result
         // if you exec the query, first you get a mysqli result *OBJECT*: 
         $result_obj = $db -> query($sql_query);
         // next you pull out the row out of this object as an associative array:
         $row = $result_obj -> fetch_assoc(); 
         //finally you assign the retrieved value as a property of your user:            
         $this->username = $row['username'];
  }
}
//be careful NOT to pass a reference here!!
$some_user = new user(1,$db); // NO ampersand here! passing by ref is deprecated!