I want to be able to call a function which connects to my database, without creating multiple objects, including or having to write the same construct in each class. I Basically want to call a construct function in other classes. like this below.
class Database{
public function __construct(){
$this->conn = new mysqli("host", "user", "password", "db");
// Check connection
if (!$this->conn) {
die("Connection failed: ".mysqli_connect_error());
}
}
}
class User{
// call Database->__construct();
}
class OtherClass{
// call Database->__construct();
}
ofcourse this isn't the way to go but i don't really know what would be a viable way.
I thought maybe this would work. but it doesn't Making a new Database object in class to construct a connection
class Database{
public function __construct(){
$this->conn = new mysqli("host", "user", "password", "db");
// Check connection
if (!$this->conn) {
die("Connection failed: ".mysqli_connect_error());
}
}
}
class User{
$conn = new Database();
}
Dependecy injection or constructor injection seems like a nice solution. But i don't know if it's made for something like this and how to apply it.
class Database{
public function connection(){
$this->conn = new mysqli("host", "user", "password", "db");
// Check connection
if (!$this->conn) {
die("Connection failed: ".mysqli_connect_error());
}
}
}
class User{
private $db;
public function __construct(Database $conn){
$this->db = $conn;
}
}
$databasewith your database connection in it, and simply use that everywhere. Why not? Works very well.