PHP Constants

sa sahaya jerish Updated 17 Oct 2026
10 min read ·Lesson 57 of 109
In this post

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 18 means 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

AspectVariableConstant
Syntax$pricePRICE (no $)
Can change after creationYesNo
ScopeLocal to the function or global scopeAvailable everywhere
Defined withAssignment (=)const or define()
Naming conventioncamelCase or snake_caseUPPER_SNAKE_CASE
Can be undefinedYes, 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

  • const defines 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 text APP_NAME. Use concatenation or sprintf().

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 if blocks, 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()

Featureconstdefine()
When it is definedCompile timeRuntime
ValueConstant expressions onlyAny expression
Inside if, loops, functionsNot allowed — top level of a file (or in a class) onlyAllowed
Dynamic nameNoYes
Class constantsYes (const inside a class)No
NamespaceUses the current namespace automaticallyMust include the namespace in the name string
Readability and static analysisBetter — editors and tools understand it directlyWeaker

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_NAME and app_name are 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

FunctionPurpose
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:

ConstantMeaningExample Value
PHP_VERSIONCurrent PHP version8.5.1
PHP_MAJOR_VERSION, PHP_MINOR_VERSIONVersion parts8, 5
PHP_OS_FAMILYOperating system familyLinux, Windows, Darwin
PHP_EOLLine ending for the current OS"\n"
DIRECTORY_SEPARATORPath separator/ or ``
PHP_INT_MAX, PHP_INT_SIZEInteger limits9223372036854775807, 8
PHP_FLOAT_EPSILONFloat precision2.220446049250313E-16
E_ALL, E_WARNING, …Error reporting levelsIntegers
M_PI, M_EMath constants3.14159…
SORT_STRING, JSON_PRETTY_PRINT, …Flags for functionsIntegers

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

  1. All business rules — currency, tax rate, threshold, and fee — are constants at the top of the file. Changing a rule means editing one line.
  2. The function uses the constants directly, without parameters or global, because constants are available everywhere and cannot be changed by other code.
  3. 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.
  4. %% 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; use define() 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

0 Comments

Reviewed before they appear

No comments yet.

PHP
PHP Home PHP Switch PHP Match Alternative Syntax PHP Loops While Loop Do While Loop For Loop Foreach Loop Nested Loops Break Statement PHP Home PHP Intro PHP Install PHP Built-in Web Server PHP Syntax PHP Tags PHP and HTML PHP Comments PHP Multiline Comments PHP Variables Variables Scope PHP Casting Logical Operators Null Coalescing Operator Spaceship Operator Operator Precedence Continue Statement Modify Strings PHP If...Else...Elseif PHP If Modify Strings PHP If Operators PHP Functions Concatenate Strings PHP If...Else Slicing Strings User-defined Functions Slicing Strings PHP Shorthand if Escape Characters Default Argument Values PHP Nested if Pass by Reference String Interpolation Named Arguments PHP File Upload Variadic Functions Return Values Search in Strings Multibyte Strings Type Declarations in Functions PHP Numbers PHP Math PHP Floats PHP Random Numbers PHP Constants PHP Properties PHP Methods PHP Constructor Constructor Property Promotion PHP Cookies PHP Destructor PHP Access Modifiers Readonly Properties PHP Sessions PHP Inheritance Method Overriding PHP Filters The final Keyword CSRF Protection PHP Filters Advanced Session Security Secure Cookies PHP Magic Constants File Upload Security PHP Callback Functions PHP Operators Filesystem Security PHP JSON Arithmetic Operators Error Reporting in Production Hiding PHP Assignment Operators PHP Configuration (php.ini) Comparison Operators PHP Command Line (CLI) PHP Exceptions Increment / Decrement Operators Migrating to PHP 8 PHP Form Validation PHP Form Required PHP Form URL/E-mail Error Handling Form Input Sanitizing Escaping Output (htmlspecialchars) Custom Error Handler Checkbox, Radio and Select Inputs Sticky Forms PHP Form Complete PHP Date and Time Date Formatting Error Logging HTTP Headers and Redirects Output Buffering Sending Email PHP cURL Consuming REST APIs PHP Generators
Ask about this post
AI Ask about this post

Ask questions about PHP Constants and get answers drawn from it.

Signed-in readers only.