好吧,您应该能够从$_GLOBALS
另一个线程中提到的那样获取它。如果您将设置重组为:
$settings = array(
'application' => array(
'db' => array(
'dbname' => 'band',
'driver' => 'mysql',
'user' => 'root',
'password' => 'root',
'host' => '127.0.0.1'
)
)
);
然后,如果我正确理解您,您可以轻松地做您所说的……例如:
class Database
{
protected $hostname;
protected $username;
protected $password;
protected $database;
protected $driver;
protected $dbname;
function __construct( $database, $options = array())
{
$options = array_merge($_GLOBALS['settings'][$application]['db'], $options);
$this->setOptions($options);
}
public function getConnection()
{
if(!$this->database)
{
$this->database = new PDO($this->getDsn(), $this->username, $this->password);
}
return $this->database;
}
public function setOptions(array $options)
{
foreach($options as $name => $value)
{
$method = 'set'.$name;
if(method_exists($this, $method))
{
$this->$method($value);
}
}
}
public function setHost($host)
{
$this->host = $host;
}
public function setUsername($username)
{
$this->username = $username;
}
public function setPassword($password)
{
$this->password = $password;
}
public function setDriver($driver)
{
$this->driver = $driver;
}
public function setDbname($dbname)
{
$this->dbname = $dbname;
}
public function getDsn()
{
return sprintf('%s:host=%s;dbname=%s', $this->driver, $this->host, $this->dbname);
}
}