几个选项,如提到的那些,包括.ini文件(使用parse_ini_file()等)、XML(可能与SimpleXML的一些混合物),但我更喜欢将配置保留在原生 PHP 中。
该include()构造允许一个return从包含的文件。这使您可以:
配置文件
return [
'foo' => [
'bar' => [
'qux' => true,
],
'zip' => false,
],
];
别处.php
function loadConfig($file) {
if (!is_file($file)) {
return false;
}
return (array) call_user_func(function() use($file) {
// I always re-scope for such inclusions, however PHP 5.4 introduced
// $this rebinding on closures so it's up to you
return include($file);
});
}
$config = loadConfig('config.php');
if ($config['foo']['bar']['qux']) {
// yeop
}
if ($config['foo']['zip']) {
// nope
}
需要特别小心,因为当您尝试取消引用不存在的维度时,PHP 会在您身上大便:
if ($config['i']['am']['not']['here']) { // poop
}
创建一个包装类/函数来管理您需要的配置是相当简单的。您可以添加对级联配置(在ASPweb.config世界中的一种)、缓存等的支持。