在对php课程进行研究之后,我一直坚持为什么我的php课程只会以一种方式工作而不是我期望的。我希望能够在创建类的新实例时传递ini文件位置。 以下代码抛出parse_ini_file打开文件错误。
class MyPDO extends PDO {
public function __construct($file){
//print $file returns '/usr/local/www/config/db.ini'
if (!$settings = parse_ini_file($file, TRUE)) throw new
exception('Unable to open ' . $file . '.');
$dns = $settings['database']['driver'] . ':host=' .
$settings['database']['host'];
parent::__construct($dns, $settings['database']['username'],
$settings['database']['password']);
}
}
try {
$conn_login = new MyPDO('/usr/local/www/config/db.ini');
$conn_login->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
然而,以下内容将按预期工作;
class MyPDO extends PDO{
public function __construct($file){
$file = '/usr/local/www/config/db.ini'; //added to make work
if (!$settings = parse_ini_file($file, TRUE)) throw new
exception('Unable to open ' . $file . '.');
$dns = $settings['database']['driver'] . ':host=' .
$settings['database']['host'];
parent::__construct($dns, $settings['database']['username'],
$settings['database']['password']);
}
}
try {
$conn_login = new MyPDO('/usr/local/www/config/db.ini');
$conn_login->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}