Checking if constant is defined

suggest change

Simple check

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"
}

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:


Constants:
* Checking if constant is defined

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
34 Constants
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR