1

多年来,我一直在程序上使用 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,但重复连接到数据库似乎也没有必要。

4

1 回答 1

0
//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!
于 2013-11-02T23:31:30.110 回答