env.class.php 支持PHP5.4
class Env
{
const ENV_PREFIX = 'PHP_';
public static function loadFile($filePath)//:void
{
if (!file_exists($filePath)) throw new Exception('配置文件' . $filePath . '不存在');
//返回二位数组
$env = parse_ini_file($filePath, true);
foreach ($env as $key => $val) {
$prefix = static::ENV_PREFIX . strtoupper($key);
if (is_array($val)) {
foreach ($val as $k => $v) {
$item = $prefix . '_' . strtoupper($k);
putenv("$item=$v");
}
} else {
putenv("$prefix=$val");
}
}
}
public static function get($name, $default = null)
{
$result = getenv(static::ENV_PREFIX . strtoupper(str_replace('.', '_', $name)));
if (false !== $result) {
if ('false' === $result) {
$result = false;
} elseif ('true' === $result) {
$result = true;
}
return $result;
}
return $default;
}
}
此方法来源于TP5框架,做了改写并优化,适用于非框架下PHP程序的配置文件
.env文件内容示例:
[app]
debug = true
apiUrl = http://localhost:999
使用方法:
Env::loadFile("./.env");
$app_api_url = Env::get('app.apiUrl');



