PHP Constants
What Is a Constant? In simple terms: A constant is a name for a value that never changes while the program runs — such as a tax rate, a maximum upload size, or the name of the application. Technically
What Is a Constant?
In simple terms: A constant is a name for a value that never changes while the program runs — such as a tax rate, a maximum upload size, or the name of the application.
Technically: A constant is an identifier bound to a value once. After it is defined, it cannot be reassigned or undefined for the rest of the script's execution. Constants are global: they can be used anywhere, including inside functions and classes, without importing them.
Why Constants Exist
Consider a script that uses the number 18 in several places:
$tax = $subtotal * 18 / 100;
// ... 200 lines later ...
echo "Includes 18% GST";
Problems with this "magic number":
- A reader cannot tell what
18means without context. - If the rate changes, every occurrence must be found and updated, and missing one creates inconsistent results.
- Nothing prevents code from accidentally changing a variable holding the rate.
A constant solves all three:
const GST_RATE_PERCENT = 18;
$tax = $subtotal * GST_RATE_PERCENT / 100;
echo "Includes " . GST_RATE_PERCENT . "% GST";
The value has a meaningful name, is defined in one place, and cannot be modified while the script runs.
Constants vs Variables
| Aspect | Variable | Constant |
|---|---|---|
| Syntax | $price | PRICE (no $) |
| Can change after creation | Yes | No |
| Scope | Local to the function or global scope | Available everywhere |
| Defined with | Assignment (=) | const or define() |
| Naming convention | camelCase or snake_case | UPPER_SNAKE_CASE |
| Can be undefined | Yes, with unset() | No |
Defining Constants With const
Syntax
const NAME = value;
Example
<?php
const APP_NAME = "GoCourse";
const MAX_UPLOAD_MB = 10;
const TAX_RATE = 0.18;
const MAINTENANCE_MODE = false;
echo APP_NAME . "\n";
echo "Upload limit: " . MAX_UPLOAD_MB . " MB\n";
var_dump(TAX_RATE, MAINTENANCE_MODE);
Output
GoCourse
Upload limit: 10 MB
float(0.18)
bool(false)
How It Works
constdefines the constant when the file is compiled, before any code in it runs.- A constant is used by writing its name without a
$. - Constants can hold scalars (
int,float,string,bool),null, arrays, and enum cases. - Constants cannot be interpolated in strings:
"Welcome to APP_NAME"prints the textAPP_NAME. Use concatenation orsprintf().
Expressions in const
const values may be constant expressions — calculations using literals and other constants:
<?php
const MAX_UPLOAD_MB = 10;
const BYTES_PER_MB = 1024 * 1024;
const MAX_UPLOAD_BYTES = MAX_UPLOAD_MB * BYTES_PER_MB;
const SECONDS_PER_DAY = 24 * 60 * 60;
const GREETING = "Welcome to " . "GoCourse";
echo MAX_UPLOAD_BYTES . "\n";
echo SECONDS_PER_DAY . "\n";
echo GREETING . "\n";
Output
10485760
86400
Welcome to GoCourse
Writing 24 * 60 * 60 instead of 86400 documents how the number was derived. The calculation happens at compile time.
Function calls are not allowed in const values:
<?php
const START_TIME = time(); // Fatal error: Constant expression contains invalid operations
Use define() for values that must be computed at runtime.
Array Constants
<?php
const ALLOWED_IMAGE_TYPES = ['jpg', 'jpeg', 'png', 'webp'];
const ROLE_LABELS = [
'admin' => 'Administrator',
'editor' => 'Editor',
'viewer' => 'Read-only',
];
echo ALLOWED_IMAGE_TYPES[2] . "\n";
echo ROLE_LABELS['editor'] . "\n";
var_dump(in_array('gif', ALLOWED_IMAGE_TYPES, true));
echo count(ALLOWED_IMAGE_TYPES) . " types allowed\n";
Output
png
Editor
bool(false)
4 types allowed
Array constants are useful for fixed lookup tables and allow-lists. The array itself cannot be modified: ALLOWED_IMAGE_TYPES[] = 'gif'; is an error.
Defining Constants With define()
Syntax
define(string $constant_name, mixed $value): bool
Example
<?php
define('APP_ENV', 'production');
define('REQUEST_START', microtime(true));
define('DEBUG', getenv('APP_DEBUG') === 'true');
echo APP_ENV . "\n";
var_dump(is_float(REQUEST_START));
var_dump(DEBUG);
Output (when the environment variable APP_DEBUG is not set)
production
bool(true)
bool(false)
How define() Differs
define() is a function that runs at runtime. That means:
- The value can be any runtime expression, including function calls (
microtime(true),getenv(...)). - The name can be built dynamically, such as
define('PREFIX_' . $name, $value). - It can be called conditionally, inside
ifblocks, functions, or loops.
<?php
if (!defined('UPLOAD_DIR')) {
define('UPLOAD_DIR', __DIR__ . '/uploads');
}
echo UPLOAD_DIR;
This pattern provides a default value that another file (such as a local configuration file) may have already defined.
const vs define()
| Feature | const | define() |
|---|---|---|
| When it is defined | Compile time | Runtime |
| Value | Constant expressions only | Any expression |
Inside if, loops, functions | Not allowed — top level of a file (or in a class) only | Allowed |
| Dynamic name | No | Yes |
| Class constants | Yes (const inside a class) | No |
| Namespace | Uses the current namespace automatically | Must include the namespace in the name string |
| Readability and static analysis | Better — editors and tools understand it directly | Weaker |
Recommendation: use const by default. Use define() only when you need a runtime value, a dynamic name, or a conditional definition.
Version note: In PHP 7.x,
define()accepted a third argument to create case-insensitive constants. It was deprecated in PHP 7.3 and removed in PHP 8.0. All constants are now case-sensitive:APP_NAMEandapp_nameare different names.
Constants Are Global
Unlike variables, constants are visible inside functions without global or parameters:
<?php
const CURRENCY = '₹';
const FREE_SHIPPING_ABOVE = 999;
function shippingMessage(float $cartTotal): string
{
if ($cartTotal >= FREE_SHIPPING_ABOVE) {
return "You qualify for free shipping!";
}
$remaining = FREE_SHIPPING_ABOVE - $cartTotal;
return "Add " . CURRENCY . number_format($remaining, 2) . " more for free shipping.";
}
echo shippingMessage(750) . "\n";
echo shippingMessage(1200) . "\n";
Output
Add ₹249.00 more for free shipping.
You qualify for free shipping!
Because constants cannot change, reading them from any function is safe — the problems of global variables (hidden modification, unpredictable state) do not apply.
Checking and Reading Constants Dynamically
| Function | Purpose |
|---|---|
defined('NAME') | Returns true if a constant with that name exists |
constant('NAME') | Returns the value of a constant whose name is in a string |
get_defined_constants(true) | Returns all constants, grouped by extension; your own are under 'user' |
Example
<?php
const PLAN_BASIC_LIMIT = 5;
const PLAN_PRO_LIMIT = 50;
$plan = 'PRO';
$constantName = "PLAN_{$plan}_LIMIT";
if (defined($constantName)) {
echo "Project limit: " . constant($constantName) . "\n";
}
var_dump(defined('PLAN_ENTERPRISE_LIMIT'));
print_r(get_defined_constants(true)['user']);
Output
Project limit: 50
bool(false)
Array
(
[PLAN_BASIC_LIMIT] => 5
[PLAN_PRO_LIMIT] => 50
)
constant() is useful when the constant name depends on data. For mappings like this, however, an array constant (const PLAN_LIMITS = ['basic' => 5, 'pro' => 50];) or an enum is usually clearer.
Errors With Constants
Using an Undefined Constant
<?php
echo SITE_URL;
Output
PHP Fatal error: Uncaught Error: Undefined constant "SITE_URL"
Since PHP 8.0, an undefined constant throws an Error. In PHP 7, PHP assumed you meant the string "SITE_URL" and only raised a warning — which hid typos and missing configuration. A common legacy symptom is code like $row[name], which only worked because PHP treated name as a string.
Redefining a Constant
<?php
define('MAX_ITEMS', 10);
define('MAX_ITEMS', 20);
echo MAX_ITEMS;
Output
PHP Warning: Constant MAX_ITEMS already defined in /path/script.php on line 3
10
The second definition fails with a warning and the original value is kept. Use defined() before define() when a constant may already exist.
Trying to Assign a New Value
<?php
const LIMIT = 5;
LIMIT = 10;
This is a parse error: a constant cannot appear on the left side of an assignment.
Predefined Constants
PHP and its extensions define many constants. Some of the most useful:
| Constant | Meaning | Example Value |
|---|---|---|
PHP_VERSION | Current PHP version | 8.5.1 |
PHP_MAJOR_VERSION, PHP_MINOR_VERSION | Version parts | 8, 5 |
PHP_OS_FAMILY | Operating system family | Linux, Windows, Darwin |
PHP_EOL | Line ending for the current OS | "\n" |
DIRECTORY_SEPARATOR | Path separator | / or `` |
PHP_INT_MAX, PHP_INT_SIZE | Integer limits | 9223372036854775807, 8 |
PHP_FLOAT_EPSILON | Float precision | 2.220446049250313E-16 |
E_ALL, E_WARNING, … | Error reporting levels | Integers |
M_PI, M_E | Math constants | 3.14159… |
SORT_STRING, JSON_PRETTY_PRINT, … | Flags for functions | Integers |
Example: Version-Dependent Code
<?php
if (PHP_VERSION_ID < 80200) {
exit("This application requires PHP 8.2 or newer.\n");
}
echo "Running on PHP " . PHP_VERSION . " (" . PHP_OS_FAMILY . ")" . PHP_EOL;
Output (example)
Running on PHP 8.5.1 (Linux)
PHP_VERSION_ID is an integer such as 80501 for 8.5.1, which is easy to compare. In applications managed with Composer, the PHP version requirement is normally declared in composer.json instead.
Constants such as JSON_PRETTY_PRINT are flags: named integers that you combine with |, as in json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE). Named flags make function calls readable compared with raw numbers.
Constants in Classes and Enums (Preview)
Constants that belong to a specific concept are usually defined inside a class:
<?php
class Order
{
public const STATUS_PENDING = 'pending';
public const STATUS_PAID = 'paid';
public const MAX_ITEMS = 50;
}
echo Order::STATUS_PAID . "\n";
echo Order::MAX_ITEMS . "\n";
Output
paid
50
Class constants are grouped with the code they describe and accessed with ClassName::CONSTANT. For a fixed set of related values such as statuses, PHP 8.1 enums provide even stronger guarantees. Both are covered in PHP Class Constants and PHP Enums.
Constants and Configuration
Constants are a good fit for values that are part of the code's rules: limits, fixed rates, allowed types, and labels.
They are not a good place for secrets and environment-specific settings written directly in source files:
<?php
// Avoid: secrets in source code end up in version control
const DB_PASSWORD = 'Sup3rS3cret!';
Read such values from the environment (or a configuration file that is not committed to version control):
<?php
define('DB_HOST', getenv('DB_HOST') ?: 'localhost');
define('DB_PASSWORD', getenv('DB_PASSWORD') ?: '');
getenv() returns false when the variable is not set, so ?: provides a fallback. Frameworks such as Laravel and Symfony load these values from .env files that are excluded from Git.
Practical Example: Checkout Rules
<?php
const CURRENCY = '₹';
const GST_RATE_PERCENT = 18;
const FREE_SHIPPING_ABOVE = 999;
const SHIPPING_FEE = 79;
function checkoutSummary(float $subtotal): string
{
$tax = round($subtotal * GST_RATE_PERCENT / 100, 2);
$shipping = $subtotal >= FREE_SHIPPING_ABOVE ? 0 : SHIPPING_FEE;
$total = $subtotal + $tax + $shipping;
return sprintf(
"Subtotal %1\$s%2\$.2f | GST %3\$d%% %1\$s%4\$.2f | Shipping %1\$s%5\$.2f | Total %1\$s%6\$.2f",
CURRENCY,
$subtotal,
GST_RATE_PERCENT,
$tax,
$shipping,
$total
);
}
echo checkoutSummary(850) . "\n";
echo checkoutSummary(1200) . "\n";
Output
Subtotal ₹850.00 | GST 18% ₹153.00 | Shipping ₹79.00 | Total ₹1082.00
Subtotal ₹1200.00 | GST 18% ₹216.00 | Shipping ₹0.00 | Total ₹1416.00
Step-by-Step Explanation
- All business rules — currency, tax rate, threshold, and fee — are constants at the top of the file. Changing a rule means editing one line.
- The function uses the constants directly, without parameters or
global, because constants are available everywhere and cannot be changed by other code. sprintf()uses numbered arguments (%1$s) so the currency symbol can be reused several times. Inside a double-quoted PHP string, each$must be escaped as\$so PHP does not try to interpolate a variable.%%produces a literal percent sign after the GST rate.
In larger applications, such rules usually live in class constants or configuration files, but the principle is the same: name the value once and refer to it everywhere.
Common Mistakes
Adding $ to a Constant
Effect: $APP_NAME refers to a (probably undefined) variable, not the constant.
Fix: Write constant names without $.
Expecting Interpolation
Effect: "Version: APP_VERSION" prints the name, not the value.
Fix: "Version: " . APP_VERSION or sprintf().
Using const Inside an if or Function
Effect: Parse error.
Fix: Use define() for conditional or runtime definitions.
Using Function Calls in const
Effect: Constant expression contains invalid operations.
Fix: Use define().
Relying on Case-Insensitive Constants
Effect: Code written for PHP 7 with define('X', 1, true) fails in PHP 8.
Fix: Use one consistent, uppercase name.
Storing Secrets in Constants in Source Code
Effect: Credentials leak through version control and shared code.
Fix: Read secrets from environment variables or untracked configuration files.
Best Practices
- Replace magic numbers and repeated literal values with well-named constants.
- Name constants in
UPPER_SNAKE_CASE. - Prefer
const; usedefine()for runtime values, dynamic names, or conditional definitions. - Use constant expressions to show how values are derived (
24 * 60 * 60). - Group constants that belong to one concept inside a class, or use an enum for fixed sets of values.
- Keep secrets and environment-specific settings out of source code.
Official reference: https://www.php.net/manual/en/language.constants.php