It is possible to get the value of a PHP constant dynamically using the constant() function. It takes a string value as the parameter and returns the value for the constant if it is defined.
Using PHP’s constant() function
In a web application I was working on recently there were a number of constants defined for dealing with country based information, and stored the value of a database ID. For example:
define('SITE_ID_NZ', 1); define('SITE_ID_AU', 2); define('SITE_ID_US', 3); define('SITE_ID_CA', 4);
Elsewhere in the code, the country code only is stored and passed around the place so there needs to be a way to construct the above constants in code to get the database id. Enter the constant() function. This first example would echo the value for the SITE_NZ constant:
$country_code = 'NZ'; // ... some other code in the meantime ... echo constant('SITE_ID_'.$country_code);
Another approach might be to have the constant value returned by a function:
function get_country_id($country_code) { return constant('SITE_ID_'. strtoupper($country_code)); }
Note the use of the strtoupper() function to ensure the country code is upper case. You may or may not need this in your own code depending on the circumstances.
If the constants are defined as part of a class they can also be retrieved using the constant function like so:
class example { const SITE_ID_NZ = 1; const SITE_ID_AU = 2; const SITE_ID_US = 3; const SITE_ID_CA = 4; function get_country_id($country_code) { return constant('self::SITE_ID_'.strtoupper($country_code)); } }
If the constant is not defined
If the constant is not defined then the call to constant() will return null, but it will also issue a warning, resulting in some output like this:
Warning: constant(): Couldn't find constant ... in ... on line ...
Therefore, a test should be done first to check if the constant is actually defined. The function example above would then be modified to look like so:
function get_country_id($country_code) { $constant = 'SITE_ID_'.strtoupper($country_code); if(defined($constant)) { return constant($constant); } else { return false; } }
And the class version would now look like this:
class example { const SITE_ID_NZ = 1; const SITE_ID_AU = 2; const SITE_ID_US = 3; const SITE_ID_CA = 4; function get_country_id($country_code) { $constant = 'self::SITE_ID_'.strtoupper($country_code); if(defined($constant)) { return constant($constant); } else { return false; } } }