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 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目