Question
In PHP, constants can be declared in two common ways:
define('FOO', 1);
or
const FOO = 1;
What are the main differences between define() and const in PHP?
When should each approach be used, and why might one be preferred over the other in certain situations?
Short Answer
By the end of this page, you will understand how PHP constants work, the practical differences between define() and const, where each can be used, and which option is usually better in modern PHP code.
Concept
In PHP, a constant is a value that cannot be changed after it is defined. Constants are useful for values that should stay fixed, such as configuration flags, application names, version numbers, status labels, or mathematical values.
PHP provides two main ways to create constants:
define()— a function callconst— a language construct
Even though both create constants, they are not identical.
Core idea
The main difference is when and where the constant is defined:
constis part of the language syntax and is typically used when the value is known in advance.define()is a function, so it runs at runtime and can be called conditionally or dynamically.
Why this matters
In real programs, this affects:
- where you are allowed to declare constants
- whether the constant name can be built dynamically
- whether the constant can be declared inside conditions or loops
- readability and code style
- support for class constants and modern PHP practices
Important practical distinction
Use const when the constant is part of the program's structure.
Use define() when you need runtime flexibility.
Common modern guidance
In most modern PHP code:
- prefer
constfor normal constant declarations - use
define()only when you need somethingconstcannot do, such as conditional or dynamic definition
Mental Model
Think of const like a label printed into the blueprint of a building. It is part of the structure of the code itself.
Think of define() like putting a label on something while the program is already running. You can decide at runtime whether to add it and what name to give it.
So:
const= built into the code designdefine()= created while the script is executing
If you already know the value and name ahead of time, const is the cleaner choice.
If the program needs to decide during execution, define() gives more flexibility.
Syntax and Examples
Basic syntax
Using const
const SITE_NAME = 'My App';
Using define()
define('SITE_NAME', 'My App');
Both create a constant named SITE_NAME.
Example: simple constant
<?php
const TAX_RATE = 0.2;
define('CURRENCY', 'USD');
echo TAX_RATE; // 0.2
echo "\n";
echo CURRENCY; // USD
Example: dynamic name with define()
<?php
$name = 'APP_MODE';
define($name, 'production');
echo APP_MODE; // production
This works because define() accepts a string for the constant name.
The equivalent with const does not work:
<?php
$name = 'APP_MODE';
const $name = 'production'; // Invalid
Example: class constant with const
<?php
class OrderStatus {
const PENDING = 'pending';
const PAID = 'paid';
}
echo OrderStatus::PAID;
const is the normal way to declare class constants.
Example: conditional definition with define()
<?php
if (!defined('DEBUG')) {
define('DEBUG', true);
}
This is useful when a constant should only be created in certain situations.
Step by Step Execution
Example
<?php
$env = 'development';
if ($env === 'development') {
define('DEBUG_MODE', true);
}
echo DEBUG_MODE;
What happens step by step
$envis created and given the value'development'.- PHP checks the
ifcondition:$env === 'development'. - The condition is
true. - PHP executes
define('DEBUG_MODE', true);. - A constant named
DEBUG_MODEis created at runtime. echo DEBUG_MODE;outputs1becausetrueis printed as1in this context.
Compare with const
This would not be valid for the same purpose:
<?php
$env = 'development';
if ($env === 'development') {
const DEBUG_MODE = true; // Invalid here
}
Why?
Because const is not meant for conditional runtime declaration like define() is.
Real World Use Cases
When const is commonly used
- Declaring application-wide fixed values
- Creating class constants
- Storing enum-like values in older PHP code
- Defining values that are known before execution starts
- Making configuration values clearer and easier to read
Example:
const APP_NAME = 'Inventory System';
const MAX_RETRIES = 3;
When define() is commonly used
- Defining constants only if they do not already exist
- Creating constants based on environment or bootstrap logic
- Building the constant name dynamically
- Working in older codebases or legacy frameworks
Example:
if (!defined('BASE_PATH')) {
define('BASE_PATH', __DIR__);
}
Typical app scenarios
- Configuration bootstrap:
define()may be used in startup files. - Class design:
constis preferred for class-level fixed values. - Feature flags:
define()can help when flags depend on runtime setup. - Readable domain values:
constworks well for status names likeSTATUS_ACTIVE.
Real Codebase Usage
In real projects, developers usually follow a simple rule:
- use
constfor constants that are part of the code design - use
define()for bootstrapping or conditional setup
Common patterns
1. Class constants
class UserRole {
const ADMIN = 'admin';
const EDITOR = 'editor';
const VIEWER = 'viewer';
}
This keeps related values grouped together.
2. Guarded bootstrap constants
if (!defined('APP_ENV')) {
define('APP_ENV', 'production');
}
This avoids redeclaring a constant if another file already defined it.
3. Validation and branching
Constants are often used to avoid magic strings:
class PaymentStatus {
const PENDING = 'pending';
const SUCCESS = 'success';
const FAILED = 'failed';
}
$status = PaymentStatus::SUCCESS;
if ($status === PaymentStatus::SUCCESS) {
echo 'Payment completed';
}
4. Configuration markers
const API_VERSION = 'v1';
This makes it easy to update shared values in one place.
Style guidance
In modern codebases, const usually improves:
- readability
- static analysis
- organization, especially inside classes
- consistency with object-oriented PHP
define() still appears often in entry files, config bootstraps, and legacy code.
Common Mistakes
1. Using const inside conditions
Broken code:
if (!defined('DEBUG')) {
const DEBUG = true; // Invalid
}
Use this instead:
if (!defined('DEBUG')) {
define('DEBUG', true);
}
2. Trying to create dynamic constant names with const
Broken code:
$name = 'VERSION';
const $name = '1.0'; // Invalid
Use this instead:
$name = 'VERSION';
define($name, '1.0');
3. Forgetting that constants cannot be changed
Broken code:
const LIMIT = 10;
LIMIT = 20; // Invalid
A constant is meant to stay fixed after definition.
4. Using global constants when a class constant is better
Less clear:
const STATUS_PAID = 'paid';
const STATUS_PENDING = 'pending';
Often better:
class OrderStatus {
const PAID = 'paid';
const PENDING = 'pending';
}
This groups related values logically.
5. Redefining a constant accidentally
Broken code:
define('APP_NAME', 'Store');
define('APP_NAME', 'Shop');
Avoid this by checking first:
if (!defined('APP_NAME')) {
define('APP_NAME', 'Store');
}
Comparisons
define() vs const
| Feature | const | define() |
|---|---|---|
| Type | Language construct | Function |
| When evaluated | As part of code structure | At runtime |
| Dynamic constant name | No | Yes |
| Conditional declaration | No | Yes |
| Works for class constants | Yes | No |
| Common in modern PHP | Yes | Sometimes |
| Best for | Fixed, known constants | Runtime or conditional constants |
Which one should you choose?
| Situation | Better choice |
|---|---|
| A fixed value known in advance | const |
| A class-level constant | const |
| A constant created only if needed | define() |
| A constant name built from a variable | define() |
| Modern application code | Usually const |
| Legacy bootstrap/config file | Often define() |
Related comparison: class constant vs regular constant
| Type | Example | Scope |
|---|---|---|
| Global constant | const APP_NAME = 'My App'; | Available globally after declaration |
| Class constant | class App { const VERSION = '1.0'; } | Accessed through the class |
Cheat Sheet
Quick rules
- Use
constfor most fixed constants in modern PHP. - Use
define()when you need runtime flexibility. - Use
constfor class constants. - Use
define()if the constant name comes from a variable. - Use
define()inside conditional logic.
Syntax
const NAME = 'value';
define('NAME', 'value');
Best-fit guide
- Known ahead of time:
const - Inside a class:
const - Conditional setup:
define() - Dynamic naming:
define()
Checks
defined('NAME');
Example patterns
const VERSION = '1.0';
if (!defined('DEBUG')) {
define('DEBUG', true);
}
Edge cases
constcannot use a variable as the constant name.constis not for conditional runtime declaration.define()cannot declare class constants.- Constants cannot be reassigned after definition.
FAQ
Is const better than define() in PHP?
Usually yes for normal constant declarations, because it is cleaner and fits modern PHP style. But define() is still useful when the constant must be created dynamically or conditionally.
Can define() be used inside an if statement?
Yes. That is one of its key advantages.
Can const be used inside a class?
Yes. In fact, const is the standard way to declare class constants.
Can I create a constant name from a variable with const?
No. For that, use define().
Are constants global in PHP?
A regular constant declared with const or define() is globally accessible after it is declared. Class constants belong to the class and are accessed with ClassName::CONSTANT_NAME.
Can a PHP constant be changed later?
No. Once a constant is defined, its value cannot be changed.
Why do many older PHP projects use define() a lot?
Older codebases often used procedural bootstrap files where runtime configuration and conditional declaration were common.
Should I use constants for every fixed value?
Not always. Use constants for values that are reused, important to meaning, or should never change. Avoid creating constants for trivial one-time literals.
Mini Project
Description
Create a small PHP configuration script for an application startup process. This project demonstrates when to use const for fixed application metadata and when to use define() for values that may depend on runtime setup.
Goal
Build a script that declares fixed app information with const and conditionally defines environment-based settings with define().
Requirements
- Declare at least two fixed constants using
const. - Conditionally define a
DEBUGconstant usingdefine(). - Output all constant values.
- Include one class that uses
constfor related status values.
Keep learning
Related questions
Are PDO Prepared Statements Enough to Prevent SQL Injection in PHP?
Learn how PDO prepared statements prevent SQL injection in PHP, what they protect, and the mistakes that still leave MySQL apps vulnerable.
Can You Bind an Array to an IN Clause in PHP PDO?
Learn how PDO handles placeholders in IN() clauses, why arrays cannot be bound directly, and the safe PHP pattern to build dynamic queries.
Choosing the Right MySQL Collation for PHP and UTF-8
Learn how MySQL character sets and collations work with PHP, and how to choose a practical UTF-8 setup for web applications.