根據think\Env摘出來改造,可以拿來直接用。
<?php
class Env
{
const ENV_PREFIX = 'PHP_';
/**
* 加載配置文件
* @access public
* @param string $filePath 配置文件路徑
* @return void
*/
public static function loadFile(string $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");
}
}
}
/**
* 獲取環境變量值
* @access public
* @param string $name 環境變量名(支持二級 . 號分割)
* @param string $default 默認值
* @return mixed
*/
public static function get(string $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;
}
}
Env::loadFile('.env');
echo Env::get('database.hostname');
---------------------------------------------------------------------
.env文件格式
[database]
hostname = 127.0.0.1
database = test
username = root
password = root123456
[payment]
wx_appid = xxxxxx
wx_appsecret = yyyyyy
wx_mchid = zzzzzz