Checking if constant is defined

suggest change

Simple check

To check whether a constant is defined, use defined(). It does not care about the constant's value. If the constant exists, it returns true even when the value is null or false.

<?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 anything; GOOD is not defined yet.
}

define("GOOD", false);

if (defined("GOOD")) {
   print "GOOD is defined"; // prints "GOOD is defined"
}

Getting all defined constants

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents