PHP Constants: An In-Depth Guide
A constant in PHP is a value that can not be changed once it is set. Constants are an essential aspect of programming and play a crucial role in maintaining the
A constant in PHP is a named value that cannot be changed once it is defined. Unlike variables, constants are not prefixed with a $, they are automatically available everywhere in the script (no scope rules), and any attempt to reassign them is either ignored or raises an error. They are ideal for fixed values such as configuration settings, API keys, version numbers, and mathematical limits.
This chapter covers how to define constants two different ways, the practical differences between them, magic constants, class constants, and the gotchas that trip people up.
Defining a constant
PHP gives you two tools: the define() function and the const keyword. Both take a name and a value.
<?php
// Using define()
define("SITE_NAME", "W3docs");
// Using the const keyword
const VERSION = "8.4";
echo SITE_NAME; // W3docs
echo PHP_EOL;
echo VERSION; // 8.4By convention, constant names are written in UPPERCASE, but PHP does not enforce this. A valid name starts with a letter or underscore, followed by letters, numbers, or underscores — exactly like a variable name, just without the $.
Notice that you reference a constant by its bare name (SITE_NAME), not with a $. Constants are case-sensitive: SITE_NAME and site_name are two different constants.
const vs define()
They produce the same kind of constant but behave differently at the language level. Knowing which to reach for avoids subtle bugs:
const | define() | |
|---|---|---|
| Evaluated at | Compile time | Run time |
Can be used inside if/loops/functions | No (top-level / class body only) | Yes |
| Name can be built dynamically | No | Yes (it's just a string argument) |
| Works inside classes | Yes (defines a class constant) | No |
Because define() runs at execution time, it's the right choice when a constant should only exist under certain conditions:
<?php
if (!defined("DEBUG")) {
define("DEBUG", true);
}
// define() can build the name dynamically — const cannot:
$key = "MAX_USERS";
define($key, 100);
echo MAX_USERS; // 100const, evaluated at compile time, is faster and the conventional choice for top-level constants in modern code.
Checking and reading constants
Before using a constant whose existence is uncertain, verify it with defined(). To fetch a constant's value when you only have its name as a string, use constant():
<?php
define("TIMEOUT", 30);
if (defined("TIMEOUT")) {
echo constant("TIMEOUT"); // 30
}Constants can hold arrays
Since PHP 7, constants are not limited to scalars (int, float, string, bool) — they can hold arrays too. This is handy for fixed lookup tables:
<?php
const ALLOWED_ROLES = ["admin", "editor", "viewer"];
echo ALLOWED_ROLES[1]; // editorSee PHP Data Types for what each value type can store.
Magic constants
PHP ships with magic constants — predefined names that change value depending on where they are used. They are written with leading and trailing double underscores:
| Constant | Resolves to |
|---|---|
__LINE__ | The current line number |
__FILE__ | The full path of the file |
__DIR__ | The directory of the file |
__FUNCTION__ | The current function name |
__CLASS__ | The current class name |
__METHOD__ | The class method name |
<?php
function greet() {
echo "Called from: " . __FUNCTION__ . PHP_EOL;
echo "On line: " . __LINE__ . PHP_EOL;
}
greet();Class constants
Constants declared inside a class belong to the class itself, not to any instance. Declare them with const and access them with the :: (scope resolution) operator:
<?php
class Circle {
const PI = 3.14159;
public function area(float $r): float {
return self::PI * $r * $r;
}
}
echo Circle::PI; // 3.14159
echo PHP_EOL;
echo (new Circle)->area(2); // 12.56636For a deeper look, read PHP Class Constants.
Constants vs variables
The two serve different jobs. A variable holds data that is expected to change; a constant locks a value in place. The key contrasts:
| Variable | Constant | |
|---|---|---|
| Prefix | $name | NAME (no sign) |
| Reassignable | Yes | No |
| Scope | Local unless made global | Global automatically |
| Case-sensitive | Yes | Yes |
Reach for a constant whenever a value is meant to stay fixed for the whole run — config flags, limits, fixed strings — so it can't be accidentally overwritten elsewhere.
Common gotchas
- Redefining a constant. Calling
define()twice on the same name raises a warning and keeps the first value; redeclaring withconstis a fatal error. Constants are write-once. - Forgetting the
$is gone. Writingecho $SITE_NAMElooks for an undefined variable, not your constant. - Undefined constants. In PHP 8+, using an undefined bare-word constant throws an
Error. Alwaysdefine()before you use, or guard withdefined().
Conclusion
PHP constants give you a safe way to store values that must never change: define them with const for ordinary top-level values or define() when you need run-time logic or a dynamic name, group fixed data in array or class constants, and lean on the built-in magic constants for debugging. Used well, they keep configuration in one place and prevent accidental reassignment.