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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?