到目前为止,我已经写了一个月的面向对象风格,现在我想知道哪种方法才是正确的 sql 查询方法。因此,例如我在类里面有函数 getPlayerData。那么哪种方式更好 - 1) 在类外执行一个 mysql 程序并将获取的数组提供给 getPlayerData 2) 在类里面完成所有程序
如果您建议第二种情况,那么我是否应该使用启动了 mysqli 实例的全局 $variable 启动每个函数?
抱歉,如果我使用的术语不正确,您可以随时纠正我。谢谢!
最佳答案
不是给每个类函数一个全局变量,你可以这样做:
class Test{
protected $mysqli = null;
function __construct($mysqli = null){
$this->mysqli = $mysqli;
}
public function setMySqli($mysqli){
$this->mysqli = $mysqli;
}
public function getSomething(){
$result = $this->mysqli->query("SELECT something FROM table");
//do something with result here
return $result;
}
}
允许您像这样使用您的对象:
$test = new Test($mysqli);
$result = $test->getSomething();
或
$test = new Test();
$test->setMySqli($mysqli);
$result = $test->getSomething();
关于php - 对象中的Mysql查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13064218/