How to Define a Constant in PHP with define()
In PHP, constants are identifiers for simple values that cannot
change during the execution of a script. This article provides a quick
and clear guide on how to define constants using the built-in
define() function, explaining its syntax, rules, and
practical code examples to help you implement them in your PHP
applications.
Syntax of the define() Function
The define() function is used to create a named constant
at runtime. The syntax is straightforward:
define(string $name, mixed $value): bool$name: The name of the constant.$value: The value of the constant. It can be a scalar value (integer, float, string, boolean) or an array (supported in PHP 7.0 and later).
Basic Example of PHP define()
To define a constant, pass the name of the constant as a string and
its corresponding value. Unlike variables, constants do not start with a
dollar sign ($).
<?php
// Defining a string constant
define("SITE_NAME", "My Awesome Website");
// Defining an integer constant
define("MAX_LOGIN_ATTEMPTS", 5);
// Accessing the constants
echo SITE_NAME; // Outputs: My Awesome Website
echo MAX_LOGIN_ATTEMPTS; // Outputs: 5
?>Key Rules and Characteristics of PHP Constants
When using the define() function, keep the following
rules in mind:
- Naming Convention: Constant names must start with a letter or an underscore, followed by any number of letters, numbers, or underscores. By convention, constant names are written in uppercase to distinguish them from variables.
- No Dollar Sign: Do not use a
$before the constant name when defining or referencing it. - Global Scope: Constants are automatically global.
They can be accessed from anywhere in your PHP script, including inside
functions, classes, and loops, without using the
globalkeyword. - Immutable: Once a constant is defined, it cannot be changed or redefined later in the execution.
- Case Sensitivity: Since PHP 8.0, constants are
strictly case-sensitive. The third parameter of
define()(which allowed for case-insensitivity) has been deprecated and removed.
Defining Array Constants
Since PHP 7.0, you can also define array constants using the
define() function:
<?php
// Defining an array constant
define("ALLOWED_ROLES", [
"admin",
"editor",
"author"
]);
// Accessing array elements
echo ALLOWED_ROLES[0]; // Outputs: admin
?>Checking if a Constant is Defined
To prevent errors when defining a constant that might already exist,
you can use the defined() function to check for its
existence:
<?php
if (!defined("API_KEY")) {
define("API_KEY", "12345-abcde");
}
?>