Using a global array inside a class

落花浮王杯 提交于 2019-12-11 07:44:02

问题


My aim is to retrieve some data from a global array which is defined in another PHP file. My code is running inside "database.php" file and the array I want to use is inside "config.php" file.

My code is as below:

config.php

$CONFIG = array();
// ...
$CONFIG["DATABASE"] = array();
$CONFIG["DATABASE"]["USERNAME"] = "user";
$CONFIG["DATABASE"]["PASSWORD"] = "pass";
$CONFIG["DATABASE"]["HOSTNAME"] = "127.0.0.1";
$CONFIG["DATABASE"]["DATABASE"] = "my_db";
// ...

database.php

require('config.php');

class Database
{
    protected   $m_Link;
    private     $m_User;
    private     $m_Pass;
    private     $m_Host;
    private     $m_Data;
    private     $m_bConnected;

    public function __construct()
    {
        global $CONFIG;
        $this->m_User = $CONFIG["DATABASE"}["USERNAME"]; // Line #16
        $this->m_Pass = $CONFIG["DATABASE"}["PASSWORD"];
        $this->m_Host = $CONFIG["DATABASE"}["HOSTNAME"];
        $this->m_Data = $CONFIG["DATABASE"}["DATABASE"];
        $this->m_bConnected = false;
        $this->Connect();
    }

    // ...
};

The error given is:

Parse error: syntax error, unexpected '}', expecting ']' in C:...\database.php on line 16

I couldn't figure out what I'm doing wrong here.

Please help me fix this error.

(Note: PHP version is 5.3.0)


回答1:


["DATABASE"} = ["DATABASE"] on all 4 lines.




回答2:


You aren't pairing your brackets properly

$this->m_User = $CONFIG["DATABASE"}["USERNAME"]; 
----------------------------------^

Should be

$this->m_User = $CONFIG["DATABASE"]["USERNAME"]; 



回答3:


You have typo error on line 16 and 3 after that.

["DATABASE"} = ["DATABASE"] should be `["DATABASE"] = ["DATABASE"]



来源:https://stackoverflow.com/questions/6184061/using-a-global-array-inside-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!