【发布时间】:2016-08-04 12:59:55
【问题描述】:
当您有多个具有查询方法的类时,关于访问数据库的“最佳实践”是什么?
全局$db变量:
$db = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
class Item {
private $id;
function __construct($id) {
$this->id = $id;
}
public function remove() {
global $db;
// queries and stuff.
}
}
或者,将$db 传递给构造函数?
$db = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$item = new Item(5,$db);
class Item {
private $id;
protected $db;
function __construct($id,$db) {
$this->id = $id;
$this->id = $db;
}
public function remove() {
// queries and stuff.
}
}
或者也许另一种方式比这两种方式都更好?
【问题讨论】:
标签: php class oop model-view-controller methods