doumaque6551 2018-11-26 12:07
浏览 121
已采纳

如何在php中编写数据库连接mysqli的依赖注入?

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

  • 写回答

3条回答 默认 最新

  • du5114 2018-11-26 12:46
    关注

    You're not passing Database instance when you're trying to instantiate Dummy object.

    It should look like this:

    <?php
    
    $host = 'localhost';
    $user = 'root';
    $pass = '';
    $dbname = 'db';
    
    $db = new Database($host,$user,$pass,$dbname);
    $test = new Dummy($db);
    echo $test->get_test_yada();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog