栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

PHP 非框架下.env配置文件应用

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP 非框架下.env配置文件应用

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');

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/276915.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号