To check if constant is defined use the defined
function. Note that this function doesn't care about constant's value, it only cares if the constant exists or not. Even if the value of the constant is null
or false
the function will still return true
.
<?php
define("GOOD", false);
if (defined("GOOD")) {
print "GOOD is defined" ; // prints "GOOD is defined"
if (GOOD) {
print "GOOD is true" ; // does not print anything, since GOOD is false
}
}
if (!defined("AWESOME")) {
define("AWESOME", true); // awesome was not defined. Now we have defined it
}
Note that constant becomes "visible" in your code only after the line where you have defined it:
<?php
if (defined("GOOD")) {
print "GOOD is defined"; // doesn't print anyhting, GOOD is not defined yet.
}
define("GOOD", false);
if (defined("GOOD")) {
print "GOOD is defined"; // prints "GOOD is defined"
}
To get all defined constants including those created by PHP use the get_defined_constants
function:
<?php
$constants = get_defined_constants();
var_dump($constants); // pretty large list
To get only those constants that were defined by your app call the function at the beginning and at the end of your script (normally after the bootstrap process):
<?php
$constants = get_defined_constants();
define("HELLO", "hello");
define("WORLD", "world");
$new_constants = get_defined_constants();
$myconstants = array_diff_assoc($new_constants, $constants);
var_export($myconstants);
/*
Output:
array (
'HELLO' => 'hello',
'WORLD' => 'world',
)
*/
It's sometimes useful for debugging