Current Location: Home> Latest Articles> Use defined() to check the relationship between a constant and get_defined_constants()

Use defined() to check the relationship between a constant and get_defined_constants()

M66 2025-05-22

The defined() function is used to check whether the specified constant has been defined. This function returns a Boolean value, true if the constant is defined, otherwise false .

grammar:

 defined(string $name): bool
  • $name : The name of the constant, passed in as a string.

Example:

 <?php
define("SITE_URL", "http://m66.net");

if (defined("SITE_URL")) {
    echo "constant SITE_URL Defined,The value is:" . SITE_URL;
} else {
    echo "constant SITE_URL Undefined";
}
?>

In the above code, we first define the constant SITE_URL using define() , and then check if it is defined via defined() . The result will output "Constant SITE_URL is defined with the value: http://m66.net" .

If we try to check an undefined constant, defined() returns false .

 <?php
if (defined("NON_EXISTENT_CONSTANT")) {
    echo "constant NON_EXISTENT_CONSTANT Defined";
} else {
    echo "constant NON_EXISTENT_CONSTANT Undefined";
}
?>

The output result is "constant NON_EXISTENT_CONSTANT undefined" because the constant is not defined.

2. The function of get_defined_constants() function

The get_defined_constants() function returns an array containing all currently defined constants, including built-in constants and user-defined constants. This function is very useful for debugging and viewing existing constants in the system.

grammar:

 get_defined_constants(bool $categorize = false): array
  • $categorize (optional): If set to true , the returned array is grouped by category.

Example:

 <?php
define("SITE_NAME", "m66.net");
define("DEBUG_MODE", true);

$constants = get_defined_constants();

echo "<pre>";
print_r($constants);
echo "</pre>";
?>

After running the code, you will see all the currently defined constants, including the PHP built-in constants and our custom SITE_NAME and DEBUG_MODE constants.

Classification constants:

If we set $categorize to true , the returned array will be grouped by category and constants will be stored by group. As shown below:

 <?php
$categorized_constants = get_defined_constants(true);
echo "<pre>";
print_r($categorized_constants);
echo "</pre>";
?>

3. The relationship between defined() and get_defined_constants()

Both defined() and get_defined_constants() involve checking and operating constants, but their functions are different.

  • defined() is used to check whether a constant is defined. It returns a Boolean value, which is suitable for checking a single constant.

  • get_defined_constants() is used to get all defined constants and returns an array, suitable for viewing or debugging all constants.

For example, we can list all constants by get_defined_constants() and combine defined() to verify whether some constants exist.

Example: