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:
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:
Another approach might be to have the constant value returned by a function:
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:
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:
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:
And the class version would now look like this:
0 comments:
Post a Comment