Php 未定义的属性:MySQLDatabase::$db\u config

Php 未定义的属性:MySQLDatabase::$db\u config,php,Php,我不知道为什么我会出现这个错误,我已经挣扎了5个小时如何修复它,请帮助。 未定义的属性:MySQLDatabase::$db\u config class MySQLDatabase { function __construct(){ if(file_exists(ROOT_PATH.'config.php')){ $db_config = json_decode(file_get_contents(ROOT_PATH.'config.php'), true);

我不知道为什么我会出现这个错误,我已经挣扎了5个小时如何修复它,请帮助。 未定义的属性:MySQLDatabase::$db\u config

class MySQLDatabase {
  function __construct(){
if(file_exists(ROOT_PATH.'config.php')){
        $db_config = json_decode(file_get_contents(ROOT_PATH.'config.php'), true);
        $this->open_connection(db_config);
}}

function open_connection() {
    $this->connection = mysqli_connect(
            $this->db_config['DBLocation'], 
            $this->db_config['DBName'], 
            $this->db_config['DBPassword'], 
            $this->db_config['DBUsername']
    );

    if(mysqli_connect_errno()) {
        echo "Connection failed: " . mysqli_connect_error();
    }
}

$db_config
是一个仅存在于其定义的方法中的变量
$this->db_config
是一个完全不同的变量,可以被类中的任何方法引用

在构造函数中,设置
$this->db_config
,而不是
$db_config

$this->db_config = json_decode(...);
然后只需调用open方法,不带任何参数:

$this->open_connection();

由于open方法引用在类级别定义的
$this->dbconfig
,因此不需要将其作为参数传递。

带有注释的正确代码:

class MySQLDatabase {
    // define class property
    protected $db_config;

    function __construct(){
        if(file_exists(ROOT_PATH.'config.php')){
            // set property value as a result of `json_decode`
            $this->db_config = json_decode(file_get_contents(ROOT_PATH.'config.php'), true);
            // json_decode can fail to return correct json
            // if your file is empty or has some bad contents
            // so we check if we really have a proper array
            if (is_array($this->db_config)) {
                // no need to pass argument to a function
                // as `db_config` property is already set
                $this->open_connection();
            }
        }
    }

    function open_connection() {
        $this->connection = mysqli_connect(
            $this->db_config['DBLocation'], 
            $this->db_config['DBName'], 
            $this->db_config['DBPassword'], 
            $this->db_config['DBUsername']
        );

        if(mysqli_connect_errno()) {
            echo "Connection failed: " . mysqli_connect_error();
        }
    }

此代码是否在类中?
$this->open\u连接(db\u配置)
db\u config
没有
$
符号。
open\u connection()
的签名中没有参数。@AlexHowansky类MySQLDatabase非常感谢,我已经为此奋斗了5个小时;\u;我可以问一下,有没有办法激活函数中的类?我需要启动一个查询,在我的函数中使用面向对象的php创建两个表,但我不知道如何。。我创建了类DatabaseQuery,将查询放在其中,但启动函数后它不会激活。。