In PHP development, constants are often used for configuration parameters, status values, and other data that should not be altered during program execution. Since the introduction of namespaces in PHP 5.3, the ability to organize code and modularize has been greatly enhanced. However, a practical issue arises: when we want to retrieve all constants defined within a specific namespace, PHP itself does not offer a direct function to filter constants by namespace. At this point, get_defined_constants() becomes a tool worth exploring in depth.
get_defined_constants() returns an associative array containing all constants defined in the current script. By passing the boolean parameter true, the constants can be grouped by category (including user-defined constants):
$constants = get_defined_constants(true);
print_r($constants['user']); // Retrieve all user-defined constants
This helps initially filter out PHP core constants, extension constants, and other unrelated content, but it is still insufficient to break down constants by namespace.
Constants defined within namespaces are actually global constants inside PHP, but their names include the namespace prefix. For example:
namespace App\Config;
const TIMEOUT = 30;
This constant will appear in the get_defined_constants() result array with the key App\Config\TIMEOUT. Therefore, we can filter the results we are interested in by using prefix string matching or regular expressions.
Here is a simple function to filter constants belonging to a specific namespace from user-defined constants:
function get_namespace_constants(string $namespace): array {
$allConstants = get_defined_constants(true);
$userConstants = $allConstants['user'] ?? [];
$filteredConstants = [];
foreach ($userConstants as $name => $value) {
if (strpos($name, $namespacePrefix) === 0) {
$filteredConstants[$name] = $value;
}
}
return $filteredConstants;
}
Example call:
print_r(get_namespace_constants('App\\Config'));
This function returns an array structured like this:
Array
(
[App\Config\TIMEOUT] => 30
[App\Config\RETRIES] => 5
)
Constants Must Be Defined First
get_defined_constants() can only retrieve constants that have already been defined before it is called. This means you must ensure the relevant files (or namespaces) have been loaded.
Naming Conventions
If multiple namespaces contain constants with the same name, filtering is based on the full name (including the namespace), so no conflicts will occur.
Can Be Encapsulated as Utility Functions or Class Methods
If you frequently need to get constants under a particular module or namespace, consider wrapping this logic into a general utility class to improve code reuse.
In some frameworks or custom frameworks, constants can serve as an alternative or supplement to configuration items. You can combine get_namespace_constants() to implement automatic configuration registration. For example:
$config = get_namespace_constants('App\\Config');
file_put_contents('https://m66.net/log/config_snapshot.json', json_encode($config));
This approach allows saving or sending configuration snapshots to remote systems, facilitating operations or troubleshooting.
Although PHP does not provide a native function to list constants by namespace directly, we can still achieve this requirement by using get_defined_constants() combined with namespace prefix rules. Mastering this technique not only enhances code organization but also proves practically valuable in framework development or large-scale systems.