Simple helper to retrieve environment variables

v0.0.1 2022-01-06 15:04 UTC

This package is auto-updated.

Last update: 2023-05-06 18:22:28 UTC


Package provides framework-agnostic helper env($key, $default) to retrieve environment variables in convenient way.

Highly inspired by Laravel env helper.


composer require zadorin/better-getenv


$varName = 'APP_ENV';
$defaultValue = 'prod';

$value = env($varName, $defaultValue);

Second parameter can be a function. In that case helper will use result of this function as default value:

$value = env('CACHE_STORAGE', function () {
    return env('APP_ENV', 'prod') === 'prod' ? 'redis' : 'file';

Usage Notes

Helper will search variable in $_ENV first, using getenv() as fallback.

If env() function already exists in your codebase, you can use namespaced call with same signature:

$value = Zadorin\env('APP_ENV', 'prod');

Helper automatically casts string values 'true', 'false' to boolean type. Similarly, 'null' string casts to null.