This question already has an answer here:
What is 'best practice' regarding accessing the database when you have multiple classes with methods that do queries?
Global $db
variable:
$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.
}
}
Or maybe, passing the $db
to the constructor?
$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.
}
}
Or maybe another way is better than both of these?
</div>