【发布时间】:2018-11-26 12:07:58
【问题描述】:
我试图写写依赖注入,但类文件出错。如何正确编写数据库连接类并将其用作依赖注入?请检查以下错误。如何编写一次连接并在 php 文件中到处调用它。
数据库.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;
}
}
代码:
$test = new Dummy();
echo $test->get_test_yada();
错误
PHP 致命错误:未捕获的 TypeError:参数 1 传递给 Dummy::__construct() 必须是数据库的实例,没有给出, 在第 19 行调用 /var/www/html/apitest/index.php 并在 /var/www/html/apitest/index.php:8\n堆栈跟踪:\n#0 /var/www/html/apitest/index.php(19): Dummy->__construct()\n#1 {main}\n 在第 8 行的 /var/www/html/apitest/index.php 中抛出
【问题讨论】:
-
你有什么错误?
-
在哪里写入配置详细信息
-
您似乎忘记在
Dummy类中声明$db变量。 -
@OlegNurutdinov [2018 年 11 月 26 日星期一 17:57:25.636338] [:error] [pid 13751] [client ::1:40700] PHP 致命错误:未捕获的 TypeError:参数 1 传递给 Dummy: :__construct() 必须是 Database 的一个实例,没有给出,在第 19 行的 /var/www/html/apitest/index.php 中调用并在 /var/www/html/apitest/index.php:8\nStack 中定义跟踪:\n#0 /var/www/html/apitest/index.php(19): Dummy->__construct()\n#1 {main}\n 在 /var/www/html/apitest/index 中抛出。 php 在第 8 行
标签: php