问题
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