In large PHP projects, the management of constants is an issue that cannot be ignored. Too many hard-coded constants are not only difficult to maintain, but are also not conducive to switching configurations between different environments. This article will explore how to build a flexible and centralized constant management mechanism through PHP's get_defined_constants() function combined with environment variable constants (such as .env files or server environment variables) to improve the maintainability and configurability of the project.
During project development, constants are used to configure database connections, API addresses, encryption keys, path identification, etc. The traditional way is usually by directly defining a large number of define() constants in configuration files or entry files:
define('API_URL', 'https://api.m66.net/v1/');
define('ENCRYPTION_KEY', 's3cr3t!');
define('APP_ENV', 'production');
There are several problems with this method:
Difficult to maintain in different environments : development, testing, and production environments often require different configurations.
Information leakage risk : Sensitive constants are exposed to the code base.
Difficulty in finding and tracking : Scattered constants are difficult to manage in a unified manner.
PHP's get_defined_constants() function can return all defined constants (system and user-defined) in the current script. Used in conjunction with namespaces (by prefixes), it is easy to retrieve project-level constants:
$constants = get_defined_constants(true);
$userConstants = $constants['user'];
foreach ($userConstants as $name => $value) {
if (strpos($name, 'APP_') === 0) {
echo "$name = $value\n";
}
}
The benefits of doing this are:
A type of constant can be loaded, traversed and debugged uniformly.
Avoid duplicate naming or overwriting.
Convenient to write debug logs, generate configuration documents, etc.
To avoid hard-code sensitive information in source code, we can use environment variables to define constants. It is recommended to use the vlucas/phpdotenv library to load environment variables from .env files:
.env file example:
APP_ENV=production
APP_DEBUG=false
API_URL=https://api.m66.net/v1/
Load these variables in the PHP startup script and define them as constants:
require __DIR__ . '/vendor/autoload.php';
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
define('APP_ENV', getenv('APP_ENV'));
define('APP_DEBUG', getenv('APP_DEBUG') === 'true');
define('API_URL', getenv('API_URL'));
Through the above method, the environment variables are automatically converted into PHP constants. Then we can use get_defined_constants() to retrieve, output or cache these constant information:
function getAppConstants(string $prefix = 'APP_'): array {
$all = get_defined_constants(true);
$user = $all['user'];
return array_filter($user, function($key) use ($prefix) {
return strpos($key, $prefix) === 0;
}, ARRAY_FILTER_USE_KEY);
}
This is very practical when debugging configuration issues, generating environment snapshots, and building automated deployment scripts.
To further decouple the code, an automatic constant loading class can be built, which can read variables named with a specific prefix in the .env file and automatically define them as constants.
class ConstantLoader {
public static function loadFromEnv(string $prefix = 'APP_') {
foreach ($_ENV as $key => $value) {
if (strpos($key, $prefix) === 0) {
if (!defined($key)) {
define($key, $value);
}
}
}
}
}
// How to use
$dotenv = Dotenv\Dotenv::createImmutable(__DIR__);
$dotenv->load();
ConstantLoader::loadFromEnv();
By converting environment variables into constants and using get_defined_constants() for unified management, the flexibility, maintainability and security of constant use in PHP projects can be greatly improved. This method is particularly suitable for medium and large PHP projects with frequent team collaborative development and CI/CD deployment environment switching. With this technology, your project configuration will be more modular, traceable, and easier to debug and migrate.