Env
The Env class provides a simple and reliable way to read environment variables in Prisma PHP applications. It supports raw access through get() and typed helpers like string(), bool(), and int().
This makes configuration safer and easier to maintain when working with secrets, feature flags, app configuration, database values, API keys, debug modes, and numeric limits.
Why use Env
Centralized Config Access
Read application settings from environment variables instead of hardcoding credentials or values directly in your source files.
Safe Defaults
Every typed helper supports a default value, so your application can continue working even when a variable is missing.
Typed Access
Convert environment values into strings, booleans, and integers without repeating parsing logic in multiple files.
Works Across Sources
The class checks values from getenv(), $_ENV, and $_SERVER.
How it works
The Env class first tries to read the requested variable using getenv(). If nothing is found, it falls back to $_ENV and then $_SERVER.
When a value exists but is not already a string, the class attempts to normalize it. Boolean values become "true" or "false", scalar values are converted to strings, and unsupported types return null.
Resolution order
First source checked for the requested key.
Used if the variable is not available from getenv().
Final fallback before returning null.
API Reference
static get(string $key): ?string
Returns the raw environment value as a string, or null when the variable does not exist or cannot be normalized into a string.
Behavior:
- Checks
getenv()first. - Falls back to
$_ENVand$_SERVER. - Converts booleans into
"true"or"false". - Converts scalar values to strings.
- Returns
nullfor missing or unsupported values.
static string(string $key, string $default = ''): string
Returns an environment variable as a string. If the variable is missing or empty, the provided default value is returned.
Best for:
- App name
- Timezone
- Base URLs
- API keys
- Driver names
static bool(string $key, bool $default = false): bool
Returns an environment variable as a boolean. It accepts common boolean-like strings in a case-insensitive way.
Accepted values:
true/false1/0yes/noon/off
static int(string $key, int $default = 0): int
Returns an environment variable as an integer. If the value is missing or not numeric, the default value is returned.
Best for:
- Port numbers
- Timeouts
- Retry limits
- Pagination defaults
- Cache durations
Usage Examples
1. Read a required API key
Use string() when you expect a text value and want a safe fallback.
<?php
use PP\Env;
$openAiKey = Env::string('OPENAI_API_KEY', '');
if ($openAiKey === '') {
throw new Exception('OPENAI_API_KEY is missing.');
}
?>
2. Toggle debug mode
Use bool() for feature flags and environment switches.
<?php
use PP\Env;
$showErrors = Env::bool('SHOW_ERRORS', false);
if ($showErrors) {
ini_set('display_errors', '1');
error_reporting(E_ALL);
} else {
ini_set('display_errors', '0');
}
?>
3. Load numeric configuration
Use int() for ports, limits, intervals, and timeouts.
<?php
use PP\Env;
$port = Env::int('APP_PORT', 3000);
$maxUploadMb = Env::int('MAX_UPLOAD_MB', 20);
$sessionMinutes = Env::int('SESSION_LIFETIME', 120);
?>
4. Read a raw value directly
Use get() when you want to inspect the raw string value or handle parsing yourself.
<?php
use PP\Env;
$driver = Env::get('DB_DRIVER');
if ($driver === null) {
$driver = 'mysql';
}
?>
5. Real application bootstrap example
A common pattern is to use Env during app boot to configure runtime behavior.
<?php
declare(strict_types=1);
use PP\Env;
date_default_timezone_set(
Env::string('APP_TIMEZONE', 'UTC')
);
$showErrors = Env::bool('SHOW_ERRORS', false);
if ($showErrors) {
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
} else {
ini_set('display_errors', '0');
}
$appName = Env::string('APP_NAME', 'Prisma PHP App');
$appPort = Env::int('APP_PORT', 3000);
?>
Example Environment Variables
Here is a typical example of values you may define in your environment for use with the Env class.
APP_NAME="Prisma PHP"
APP_TIMEZONE="America/Managua"
APP_PORT=3000
SHOW_ERRORS=true
OPENAI_API_KEY="sk-..."
DB_DRIVER="mysql"
MAX_UPLOAD_MB=20
Common Patterns
Use typed helpers whenever possible
Prefer string(), bool(), and int() over manual conversion in application code.
Always provide a sensible default
Defaults make local development and deployment more resilient when a variable has not been configured yet.
Validate critical secrets explicitly
For required values like API keys or encryption secrets, check for an empty result and fail early with a clear exception.
Keep config logic near bootstrap
Read environment variables once during startup and pass the resolved values into the parts of the system that need them.
Things to watch out for
Important behavior notes
string() returns the default when the value is missing or when the value is an empty string.
If a boolean value cannot be interpreted, bool() falls back to the provided default.
int() only converts numeric values. Otherwise it returns the default.
This class reads environment values that already exist in the runtime. It does not parse a .env file by itself.
Quick Reference
Raw nullable string access.
String with fallback default.
Boolean parsing with fallback.
Integer parsing with fallback.
Example class
<?php
declare(strict_types=1);
namespace PP;
final class Env
{
/**
* Get raw env value (string) or null if missing.
*/
public static function get(string $key): ?string
{
$v = getenv($key);
if ($v !== false) {
return $v;
}
$v = $_ENV[$key] ?? $_SERVER[$key] ?? null;
if ($v === null) return null;
if (is_bool($v)) return $v ? 'true' : 'false';
if (is_scalar($v)) return (string) $v;
return null;
}
/**
* Get string env with default.
*/
public static function string(string $key, string $default = ''): string
{
$v = self::get($key);
return ($v === null || $v === '') ? $default : $v;
}
/**
* Get boolean env with default.
* Accepts: true/false, 1/0, yes/no, on/off (case-insensitive)
*/
public static function bool(string $key, bool $default = false): bool
{
$v = self::get($key);
if ($v === null) return $default;
$b = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
return $b ?? $default;
}
/**
* Get int env with default.
*/
public static function int(string $key, int $default = 0): int
{
$v = self::get($key);
if ($v === null) return $default;
return is_numeric($v) ? (int) $v : $default;
}
}
?>
Summary
Env is a lightweight configuration helper for Prisma PHP. It gives you a consistent way to read raw and typed environment values, reduce repeated parsing logic, and keep application configuration clean, safe, and predictable.