...

/

Constants

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:

<?php
const PI = 3.14; // float
define("EARTH_IS_FLAT", false); // boolean
const UNKNOWN = null; // null
define("APP_ENV", "dev"); // string
const MAX_SESSION_TIME = 60 * 60; // integer, using (scalar) expressions is ok
const APP_LANGUAGES = ["de", "en"]; // arrays
define("BETTER_APP_LANGUAGES", ["lu", "de"]); // arrays
?>

If you have already defined one constant, you can define another one based on it:

<?php
const 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 too
define("MAX_SESSION_TIME_IN_MINUTES", MAX_SESSION_TIME / 60);
const APP_FUTURE_LANGUAGES = [-1 => "es"] + APP_LANGUAGES; // array manipulations
define("APP_BETTER_FUTURE_LANGUAGES", array_merge(["fr"],BETTER_APP_LANGUAGES));
?>

...