Defining constants

suggest change

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; allowed in const since PHP 5.6
define("BETTER_APP_LANGUAGES", ["lu", "de"]); // arrays; allowed in define() since PHP 7.0

Define constant using another constant

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

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
// the above example (a function call) does not work with const:
// const TIME = time(); # fails with a fatal error! Not a constant scalar expression
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));

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

On current PHP this is a warning, and the same names become an Error in PHP 9:

Warning: Constant true already defined, this will be an error in PHP 9

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() runs at runtime. const is declared at compile time.

Thus define allows for dynamic values (i.e. function calls, variables etc.) and even dynamic names and conditional definition. A name with no namespace in it is created in the global namespace, even when the call is inside a namespace. Include the namespace in the name to define a namespaced constant.

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.

Since PHP 8.1 a const expression may also use new. Arbitrary function calls still have to go through define().

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents