Search⌘ K
AI Features

Constants

Explore how to define immutable constants in PHP using const and define, learn the conventions for naming them, and discover how to check for their existence. Understand reserved constant names and how to retrieve all user-defined and built-in constants for effective coding.

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
<?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
<?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));
?>

...