Constants
This lesson discusses all there is to know about constants, i.e., defining them, checking if they're defined and using them in PHP programs.
We'll cover the following...
Defining Constants #
Constants, by definition, are variables that cannot be modified during the execution of the script. They are created using the const
statement or the define
function.
Convention: In PHP, the convention is to use uppercase letters for constant names, e.g.,
A_CONSTANT
.
The following code snippet shows how constants are created:
Press + to interact
<?phpconst PI = 3.14; // floatdefine("EARTH_IS_FLAT", false); // booleanconst UNKNOWN = null; // nulldefine("APP_ENV", "dev"); // stringconst MAX_SESSION_TIME = 60 * 60; // integer, using (scalar) expressions is okconst APP_LANGUAGES = ["de", "en"]; // arraysdefine("BETTER_APP_LANGUAGES", ["lu", "de"]); // arrays?>
If you have already defined one constant, you can define another one based on it:
Press + to interact
<?phpconst TAU = PI * 2;define("EARTH_IS_ROUND", !EARTH_IS_FLAT);define("MORE_UNKNOWN", UNKNOWN);define("APP_ENV_UPPERCASE", strtoupper(APP_ENV)); // string manipulation is ok toodefine("MAX_SESSION_TIME_IN_MINUTES", MAX_SESSION_TIME / 60);const APP_FUTURE_LANGUAGES = [-1 => "es"] + APP_LANGUAGES; // array manipulationsdefine("APP_BETTER_FUTURE_LANGUAGES", array_merge(["fr"],BETTER_APP_LANGUAGES));?>
...