I have tried to write to write the dependency injection but the class file is getting an error. How to properly write the database connection class and use it as a dependency injection?. Please check with the following error. How to write the connection once and call it everywhere in php files.
Database.php
class Database
{
private $host ="localhost";
private $user = "root";
private $password="xxxx";
private $db="";
private $mysqli;
function __construct($host,$user,$pass,$data) {
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->data = $data;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->data);
}
public function query($query)
{
return $this->mysqli->query($query);
}
}
Dummy.php
require_once("../apitest/database.php");
class Dummy
{
protected $db;
function __construct(Database $db)
{
$this->db = $db;
}
function get_test_yada(){
return $this->db->mysqli->query("SELECT test FROM test")->fetch_object()->test;
}
}
Code:
$test = new Dummy();
echo $test->get_test_yada();
Error
PHP Fatal error: Uncaught TypeError: Argument 1 passed to Dummy::__construct() must be an instance of Database, none given, called in /var/www/html/apitest/index.php on line 19 and defined in /var/www/html/apitest/index.php:8 Stack trace: #0 /var/www/html/apitest/index.php(19): Dummy->__construct() #1 {main} thrown in /var/www/html/apitest/index.php on line 8