get_defined_constants()
This function will give you an array full of all the constants that were defined before the function was called. The keys of this array are the names and the values, of course, are the constants’ values.
This array will contain all of the constants predefined by PHP plus those from any extensions you have loaded and any constants defined in the script (through the use of define()) but not any class constants (declared through the use of const).
So it’s going to be huge for most set ups. Too big to show an example here anyway - mine showed 989 constants defined!
But you’re likely to want just the user defined constants, or perhaps just those of a certain extension. For that, you can set the second parameter to true and the array will now be categorized and presented as a multidimensional array.
define('MONKEY', 'banana'); $list = get_defined_constants(true); define('BIRD', 'worm'); var_export($list['session']); /* array ( 'DATE_ATOM' => 'Y-m-d\TH:i:sP', 'DATE_COOKIE' => 'l, d-M-y H:i:s T', 'DATE_ISO8601' => 'Y-m-d\TH:i:sO', 'DATE_RFC822' => 'D, d M y H:i:s O', 'DATE_RFC850' => 'l, d-M-y H:i:s T', 'DATE_RFC1036' => 'D, d M y H:i:s O', 'DATE_RFC1123' => 'D, d M Y H:i:s O', 'DATE_RFC2822' => 'D, d M Y H:i:s O', 'DATE_RFC3339' => 'Y-m-d\TH:i:sP', 'DATE_RSS' => 'D, d M Y H:i:s O', 'DATE_W3C' => 'Y-m-d\TH:i:sP', 'SUNFUNCS_RET_TIMESTAMP' => 0, 'SUNFUNCS_RET_STRING' => 1, 'SUNFUNCS_RET_DOUBLE' => 2, ) */ var_export($list['user']); /* array ( 'MONKEY' => 'banana', ) */
In that example, you can see that BIRD does not appear in the list. That’s because it was defined after we generated the list through calling this function.
In this next example, you’ll see that it is in the list even though it is defined inside of a function. Once our function testing() is called, the constant is defined. And since constants are global, it shows up in our list of defined constants.
Now you can see why class constants aren’t seen by get_defined_constants(); there would be conflicts all over the place. If you use define() inside of a class method, however, that constant would show up in our list (after that method is called).
function testing() { define('BIRD', 'worm'); } testing(); define('MONKEY', 'banana'); $list = get_defined_constants(true); var_export($list['user']); /* array ( 'BIRD' => 'worm', 'MONKEY' => 'banana', ) */
