PHP Defining constants


Constants are created using the const statement or the define function. The convention is to use UPPERCASE letters for constant names.

Define constant using explicit values

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

Define constant using another constant

if you have one constant you can define another one based on it:

const TAU = PI * 2;
define("APP_ENV_UPPERCASE", strtoupper(APP_ENV)); // string manipulation is ok too
// the above example (a function call) does not work with const:
// const TIME = time(); # fails with a fatal error! Not a constant scalar expression

const APP_FUTURE_LANGUAGES = [-1 => "es"] + APP_LANGUAGES; // array manipulations


Reserved constants

Some constant names are reserved by PHP and cannot be redefined. All these examples will fail:

define("true", false); // internal constant
define("false", true); // internal constant
define("CURLOPT_AUTOREFERER", "something"); // will fail if curl extension is loaded

And a Notice will be issued:

Constant ... already defined in ...

Conditional defines

If you have several files where you may define the same variable (for example, your main config then your local config) then following syntax may help avoiding conflicts:

defined("PI") || define("PI", 3.1415); // "define PI if it's not yet defined"

const vs define

define is a runtime expression while const a compile time one.

Thus define allows for dynamic values (i.e. function calls, variables etc.) and even dynamic names and conditional definition. It however is always defining relative to the root namespace.

const is static (as in allows only operations with other constants, scalars or arrays, and only a restricted set of them, the so called constant scalar expressions, i.e. arithmetic, logical and comparison operators as well as array dereferencing), but are automatically namespace prefixed with the currently active namespace.

const only supports other constants and scalars as values, and no operations.